如何避免WordPress中具有多个循环的帖子显示重复

Recently one of our users ran into the issue of having duplicate post while developing a custom theme. What he was trying to do was show the most recent post on the homepage, and then show a list of random posts in a separate loop on the same page. The issue was that the most recent post would sometime be duplicated in the random post loop. In this article, we will show you how to avoid duplicate post display when using multiple loops in WordPress.

最近,我们的一位用户在开发自定义主题时遇到重复帖子的问题。 他试图做的是在首页上显示最新的帖子,然后在同一页面上的单独循环中显示随机帖子的列表。 问题是最近的帖子有时会在随机帖子循环中重复。 在本文中,我们将向您展示在WordPress中使用多个循环时如何避免重复的帖子显示。

The trick to avoiding duplicate post display is to store the post ID from the first loop, then check against that in the second loop. Here is how you do it. Your first loop’s code need to look like this (notice the magic line):

避免重复显示帖子的技巧是存储第一个循环中的帖子ID,然后在第二个循环中对其进行检查。 这是您的操作方式。 您的第一个循环的代码需要看起来像这样(注意魔术行):


<?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
  while ($my_query->have_posts()) : $my_query->the_post();

  $do_not_duplicate = $post->ID; //This is the magic line

?>
    <!-- Do stuff... -->
<?php endwhile; ?>

Now that we have stored the post ID from the first loop under $do_not_duplicate variable, lets add a check for that in our second loop. Your second loop code should look something like this:

现在,我们已将第一个循环中的帖子ID存储在$ do_not_duplicate变量下,让我们在第二个循环中添加对它的检查。 您的第二个循环代码应如下所示:


<?php if (have_posts()) : while (have_posts()) : the_post(); 

  if( $post->ID == $do_not_duplicate ) continue; //This is the Magic Line

 ?>
   <!-- Do stuff... -->
  <?php endwhile; endif; ?>

As long as you add those two lines in there, your posts will NOT replicate. To all new theme designers, we hope this helps.

只要在其中添加这两行,您的帖子就不会重复。 对于所有新主题设计师,我们希望这会有所帮助。

翻译自: https://www.wpbeginner.com/wp-themes/how-to-avoid-duplicate-post-display-with-multiple-loops-in-wordpress/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值