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 开发人员,但我需要完成这项任务。这段代码不是我写的,只是在网上找到的。有人可以帮我只显示一次帖子或改进此代码吗?谢谢你
解决方案
如果您输出了重复的帖子:
- 这当然是因为帖子有多个类别。因此,将在多个类别中找到单个帖子。
- 为防止出现这种情况,您可以从您的类别中查询独特的帖子:
看:
//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
这应该只显示来自子类别的唯一帖子。
推荐阅读
- if-statement - if 语句中的变量赋值
- r - 如何在ggplot2中躲避的geom_bar中的类别集之间添加空格?
- javascript - 变量作为Javascript中的条件
- r - 将 PowerPoint 模板与 officedown 一起使用
- java - android studio中的文本视图正在消失
- python - 如何为 git repos 进行 pip install
- django - 姜戈。将 redis 查询移到视图之外。使查询结果可用于所有视图
- laravel - Laravel 无法加载动态库 'pdo_mysql.so'
- mysql - 使用 mysql 查询 Woocommerce 在产品描述中添加第一个类别名称
- facebook-graph-api - 通过 API 创建 Facebook 广告系列