我想创建一个循环来抓取最近的三个帖子并显示每个帖子的标题和类别。我拥有的循环目前正在为每个帖子获取正确的值,但 foreach 循环也会附加所有上一篇文章的值,因此在第三篇帖子中,它显示除了第三篇帖子独有的类别外,它还具有上一篇文章的所有类别。
为了进一步澄清 - 如果Post1被归类为A和B,Post2被归类为C和D,Post2显示它被归类为ABCD。谁能看出我做错了什么?提前谢谢。
<section class="blog-index">
<?php
$args = array('showposts' => 3);
$recent = new WP_Query( $args );
if( $recent->have_posts() ):
echo '<div class="blog-index-list">';
while ( $recent->have_posts()) : $recent->the_post();
$categories = get_the_category();
foreach($categories as $category) {
$cat .= $category->name;
};
echo '<article>
<h2><a href="'.get_the_permalink().'">' .get_the_title(). '</a></h2>
<p class="post-cats"> ' . $cat . '</p>
<img src="'.get_the_post_thumbnail().'' .
'<div class="blog-index-button et_pb_button_module_wrapper et_pb_module et_pb_button_alignment_center">
<a class="et_pb_button et_pb_button_3 et_pb_module et_pb_bg_layout_light" href="' . get_the_permalink() . '">READ POST</a>
</div>
</article>';
endwhile;
echo '</div>';
endif;
wp_reset_query();
?>
</section>
在我看来
,您没有在抓取帖子之间清除$cat变量。使用 .= 将数据追加到$cat时,需要在每次调用 foreach 之间设置 $cat = "。