hazemhazem
hazemhazem

Reputation: 111

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.

Upvotes: 3

Views: 1486

Answers (1)

Raunak Gupta
Raunak Gupta

Reputation: 10809

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!

Upvotes: 3

Related Questions