我正在尝试创建一个类别列表,但我只想列出父类别而不是子类别。我怎样才能做到这一点?到目前为止,我已经创建了一个列表,列出了所有父类和子类。
function categoryList() {
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($args);
$output .= '<ul class="category-list">';
foreach($categories as $category) {
if ($category){
$output .= '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';
}
}
$output .= '</li>';
$output .= '</ul>';
return $output;
}
答案 0 :(得分:2)
根据父类别,我认为您的意思是顶级类别。这实际上记录在Codex page for get_categories
上:您应该使用get_categories
parent => 0
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0
);
$categories = get_categories($args);
答案 1 :(得分:2)
仅列出wordpress中的顶级(父级)分类。选项'hide_empty'=&gt; 0确保列出空的顶级类别。
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0,
'hide_empty' => 0,
//'exclude' => '7',
// optional you can exclude parent categories from listing
);
$categories = get_categories( $args );
答案 2 :(得分:0)
原生的Wordpress解决方案,用于返回CURRENT父类别, 排除不必要的类别:
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);
评论:
答案 3 :(得分:0)
使用此:
$categories = get_categories( [ 'parent'=> id_parent ,'hide_empty' => 0,] );
答案 4 :(得分:0)
下面的代码将为我们提供父猫的名称和URL。
function ns_primary_cat() {
$cat_now = get_the_category();
$cat_now = $cat_now[0];
if ( 0 == $cat_now->category_parent ) {
$catname = '<span class="category"><a href="' . get_category_link( $cat_now->term_id ) . '">' . $cat_now->name . '</a></span>';
} else {
$parent_id = $cat_now->category_parent;
$parent_cat = get_category( $parent_id );
$catname = '<span class="category"><a href="' . get_category_link( $parent_id ) . '">' . $parent_cat->name . '</a></span>';
}
return $catname;
}