首页 > 解决方案 > 如何在其特定类别中显示帖子,而不是父级

问题描述

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

# 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 开发人员,但我需要完成这项任务。这段代码不是我写的,只是在网上找到的。有人可以帮我只显示一次帖子或改进此代码吗?谢谢你

标签: wordpress

解决方案


如果您输出了重复的帖子:

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

看:

//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_ids 并防止重复显示:

# 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这应该只显示来自子类别的唯一帖子。


推荐阅读