仅获取父类别 wordpress


Get only parent categories wordpress

>我正在尝试创建一个类别列表,但我只想列出父类别而不是子类别。我该怎么做?到目前为止,我已经创建了一个列表,其中列出了所有父类别和子类别。

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;
}

通过父类别,我假设你是指顶级类别。这实际上记录在 Codex 页面上,用于get_categories:您应该用parent => 0调用get_categories

$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
);
$categories = get_categories($args);

在wordpress中仅列出顶级(父级)分类。选项"hide_empty"=> 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 );

使用这个:

$categories = get_categories( [ 'parent'=> id_parent ,'hide_empty' => 0,] );
一个

原生的Wordpress解决方案,用于返回当前的父类别,排除不需要的类别:

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

评论:

  • 如果您只有一个父类别,请传递 null 而不是数组
  • 如果您想要另一个输出而不是 slug,请将其更改为返回 $primary_category-> slug;
下面的

代码将为我们提供父猫名称和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;
}