我正试图在我的单个帖子视图的底部添加一个相关帖子部分。它需要抓取当前帖子的类别,并只显示两个与这些类别匹配的帖子。我几乎做到了,但我的结果显示每个类别中有2个,而不是总共2个。
<?php if ( is_single() ) { ?>
<div class="related-posts wrapper clearfix">
<?php $categories = get_the_category();
foreach ($categories as $category) {
$cat = $category->cat_ID;
$args=array(
\'cat\' => $cat,
\'order\' =>DESC,
\'post__not_in\' => array($post->ID),
\'posts_per_page\'=>2,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$i = 0; while ($my_query->have_posts() && $i < 3) : $my_query->the_post(); ?>
<h2 class="related-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php $i++; endwhile; }
}
wp_reset_query();
?>
</div>
<?php } else {};?>
最合适的回答,由SO网友:s_ha_dum 整理而成
构建类别数组:
foreach ($categories as $category) {
$cat[] = $category->cat_ID;
}
然后将其传递给查询:
$args=array(
\'category__in\' => $cat,
\'order\' =>DESC,
\'post__not_in\' => array($post->ID),
\'posts_per_page\'=>2,
);
换句话说,将查询放在
foreach
, 不在里面。