是否仅显示WordPress父类别?

时间:2012-01-28 作者:WordPress

我在自定义wordpress页面上有以下代码:

    <?php 
    $cat_array = array();
    $args=array(
      \'post_type\' => \'post\',
      \'post_status\' => \'publish\',
      \'posts_per_page\' => 10,
      \'caller_get_posts\'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post();
        $cat_args=array(\'orderby\' => \'none\');
        $cats = wp_get_post_terms( $post->ID , \'category\', $cat_args);
        foreach($cats as $cat) {
          $cat_array[$cat->term_id] = $cat->term_id;
        }
      endwhile;
    }
    if ($cat_array) {
      foreach($cat_array as $cat) {
        $category = get_term_by(\'ID\',$cat, \'category\');
        echo \'<a href="\' . esc_attr(get_term_link($category, \'category\')) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category->name.\'</a>\'.\'<br />\';
      }
    }
    wp_reset_query();
?>
它首先按最近更新的类别的顺序列出类别。如何调整代码以仅获取父类别?

示例:

基本上,我只想显示顶级类别。例如:

类别-子类别-子类别-子子类别

只是类别。

1 个回复
SO网友:mor7ifer

这应该符合你的要求。它还没有经过测试,我只是很快就完成了,但概念就在那里。

function my_get_highest_parent( $id ) {
    $cat = get_category( $id );
    $parent = $cat->parent;

    if( $parent == 0 ) 
        return $id;
    else
        my_get_highest_parent( $parent );
}

结束