非常简单的问题:这是我的get_categories()
代码:
<?php $args = array(
\'show_option_all\' => \'\',
\'show_option_none\' => \'\',
\'orderby\' => \'ID\',
\'order\' => \'ASC\',
\'show_count\' => 0,
\'hide_empty\' => 0,
\'exclude\' => \'1\',
\'hierarchical\' => 0,
\'depth\' => 1,
\'number\' => 12
);
?>
<?php $categories = get_categories( $args ); ?>
<div class="middle-left">
<ul>
<?php for( $i=0; $i<4; $i++ ) {
echo "<li>" . $categories[$i]->{\'name\'} . "</li>";
} ?>
</ul>
</div>
<div class="middle-middle">
<ul>
<?php for( $i=4; $i<8; $i++ ) {
echo "<li>" . $categories[$i]->{\'name\'} . "</li>";
} ?>
</ul>
</div>
<div class="middle-right">
<ul>
<?php for( $i=8; $i<12; $i++ ) {
echo "<li>" . $categories[$i]->{\'name\'} . "</li>";
} ?>
</ul>
</div>
经过长时间的搜索,我找到了在没有foreach循环的情况下进入stdClass对象的方法,我想继续这样做。但我只想要顶级类别,没有子类别。
如何修改此处的参数?
最合适的回答,由SO网友:s_ha_dum 整理而成
使用get_terms
使用parent
论点从该功能的Codex页面,强调我的:
parent(integer)获取此项的直接子项(仅限显式父项为此值的项)。If 0 is passed, only top-level terms are returned. 默认值为空字符串。
未经测试,但这应该可以做到。
$categories = get_terms(
\'category\',
array(\'parent\' => 0)
);
当然,您需要添加所需的任何其他参数。
SO网友:Fellipe Sanches
用于返回当前父类别的本机Wordpress解决方案。
You do not need to use foreach outside the function...
function primary_categories($arr_excluded_cats) {
if($arr_excluded_cats == null) {
$arr_excluded_cats = array();
}
$post_cats = get_the_category();
$args = array(
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'parent\' => 0
);
$primary_categories = get_categories($args);
foreach ($primary_categories as $primary_category) {
foreach ($post_cats as $post_cat) {
if(($primary_category->slug == $post_cat->slug) && (!in_array($primary_category->slug, $arr_excluded_cats))) {
return $primary_category->slug;
}
}
}
}
//if you have more than two parent categories associated with the post, you can delete the ones you don\'t want here
$dont_return_these = array(
\'receitas\',\'enciclopedico\'
);
//use the function like this:
echo primary_categories($dont_return_these);
备注:
如果post只有一个父类别,请传递null而不是数组,如果希望另一个输出而不是slug,请将其更改为返回$primary\\u category->slug