如何显示特定类别而非父类别中的帖子

时间:2018-08-04 16:56:33

标签: wordpress

我有一个父类别,其中有很多子类别,也有很多子类别,这些类别都有帖子。我想在页面上显示第一个父类别的所有子类别标题,并且仅发布一次标题。 现在,我的代码在每次循环迭代后都会多次显示帖子,但是我只想显示一次。 这是我的代码段

# get child categories
$sub_cats = get_categories( array(
    'child_of' => $parent_id,
    'hide_empty' => 0
) );
if( $sub_cats ){
    foreach( $sub_cats as $cat ){

        echo '<h3>'. $cat->name .'</h3>';

        # get posts from category
        $myposts = get_posts( array(
            'numberposts' => -1,
            'category'    => $cat->cat_ID,
            'orderby'     => 'post_date',
            'order'       => 'DESC',
        ) );
        # show posts
        global $post;
        foreach($myposts as $post){
            setup_postdata($post);
            echo '<li class = "test"><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
        }
    }

    wp_reset_postdata(); 
}

我不是WordPress开发人员,但我需要执行此任务。我没有编写此代码,只是在互联网上找到它。 有人可以帮我只显示一次帖子或改进此代码吗? 谢谢

1 个答案:

答案 0 :(得分:0)

如果输出的帖子重复:

  • 这当然是因为帖子具有多个类别。因此,一个帖子可以在多个类别中找到。
  • 为防止这种情况,您可以查询类别中的独特帖子:

请参阅:

//get terms from taxonomy category
$sub_cats = get_categories( [
    'child_of' => $parent_id,
    'hide_empty' => 0
] );

//wp-query post from your categories
$query    = new WP_Query( [ 'category__in' => array_map( function ( $o ) {
    return $o->term_id;
}, $sub_cats ) ] );

//only unique - never tested this
add_filter('posts_distinct', function(){return "DISTINCT";});

//your posts
$posts = $query->posts;

如果您需要保持循环原样,则可以使用数组存储显示的post_id,并防止重复显示:

# get child categories
$sub_cats = get_categories( array(
    'child_of' => $parent_id,
    'hide_empty' => 0
) );
$sub_cats_unique_posts = []; //array to store displayed post IDs

if( $sub_cats ){
    foreach( $sub_cats as $cat ){

        echo '<h3>'. $cat->name .'</h3>';

        # get posts from category
        $myposts = get_posts( array(
            'numberposts' => -1,
            'category'    => $cat->cat_ID,
            'orderby'     => 'post_date',
            'order'       => 'DESC',
        ) );
        # show posts
        global $post;
        foreach($myposts as $post){
            if(!in_array($post->ID, $sub_cats_unique_posts)){ //if not displayed already
                setup_postdata($post);
                echo '<li class = "test"><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
                $sub_cats_unique_posts[] = $post->ID; //add this post ID to displayed one
            }
        }
    }

    wp_reset_postdata();
}

这应该只显示来自$parent_id个子类别的唯一帖子。