当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to list wordpress categories id and name inside an array?

问题描述:

This is my code to get categories ids and names:

<?php

$categories = get_categories('orderby=name&hide_empty=0');

foreach ($categories as $category):

$catids = $category->term_id;

$catname = $category->name;

endforeach;

?>

Now, I want to list ids and names inside array:

array(

$catids => $catname,

);

I want the array to be like:

array(

'1' => 'Ctegory 1',

'2' => 'Ctegory 2',

'3' => 'Ctegory 3',

);

which is 1,2,3 are categories ids and Ctegory 1, Ctegory 2, Ctegory 3 are categories names

Any help will be appreciated.

Thanks.

网友答案:

I think you are looking for something like this.

<?php
$order_options = array('all' => 'All Categories');
$categories = get_categories('orderby=name&hide_empty=0');
foreach ($categories as $category):
    $catids = $category->term_id;
    $catname = $category->name;
    $order_options[$catids] = $catname;
endforeach;

print_r($order_options);

And if you want to generate a dropdown of categories with $order_options you can use it like this:

<select name="">
    <?php foreach ($order_options as $cat_id => $cat_name)
    {
        ?>
        <option value="<?php echo $cat_id ?>"><?php $cat_name ?></option>
<?php } ?>
</select>

Hope this helps!

分享给朋友:
您可能感兴趣的文章:
随机阅读: