【问题标题】:How to list wordpress categories id and name inside an array?如何在数组中列出 wordpress 类别 ID 和名称?
【发布时间】:2017-05-31 09:33:58
【问题描述】:

这是我获取类别 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 是类别 ID,类别 1、类别 2、类别 3 是类别名称

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

【问题讨论】:

    标签: php arrays wordpress


    【解决方案1】:

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

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

    希望这会有所帮助!

    【讨论】:

    • 我希望数组是这样的:array('1' => 'Ctegory 1', '2' => 'Ctegory 2', '3' => 'Ctegory 3', );其中 1,2,3 是类别 ID,类别 1、类别 2、类别 3 是类别名称
    • @hazemhazem:是的,你将如何得到它。
    • 对不起,如果我的问题不清楚,那是我的完整代码,希望你能帮忙,我想列出 select 中的所有类别:term_id; $catnme = $类别->名称;结束; $order_options = array('all' => '所有类别', $catslug => $catnme, ); foreach( $order_options as $value => $label ) { echo ""; } ?>
    • @hazemhazem:所以你想要一个类别下拉列表,对吧?
    • 是的,下拉菜单使用 $order_options = array( 'all' => 'All Categories', $catslug => $catnme, );我想提取 $catslug 中的 id 和 $catnme 中的名称以获得最终结果: $order_options = array( 'all' => 'All Categories', '1' => 'Ctegory 1', '2' => '类别 2', '3' => '类别 3', );
    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多