如何在数组中列出wordpress类别的id和名称?

时间:2017-01-16 14:05:16

标签: php arrays wordpress

这是获取类别ID和名称的代码:

<?php 
$categories = get_categories('orderby=name&hide_empty=0');
foreach ($categories as $category):
    $catids = $category->term_id;
    $catname = $category->name;
endforeach;
?>

现在,我想列出数组中的ID和名称:

array(
    $catids => $catname,
);

我希望数组如下:

array(
    '1' => 'Ctegory 1',
    '2' => 'Ctegory 2',
    '3' => 'Ctegory 3',
);

这是1,2,3类别ids和Ctegory 1,Ctegory 2,Ctegory 3是类别名称

任何帮助将不胜感激 感谢。

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找类似的东西。

<?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);

如果您想使用$order_options生成类别下拉列表,可以像这样使用它:

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

希望这有帮助!