WordPress停止循环获取帖子

时间:2016-12-14 21:49:37

标签: php mysql wordpress loops while-loop

这是我的代码来获取第1类的帖子:

<?php query_posts('cat=1'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <h2><?php the_title(); ?></h2>

<?php endwhile; endif; ?>

但我有3篇博客文章,它显示所有3篇博客文章标题。我希望它只显示1篇博文。我怎么能在while循环中做到这一点?感谢

2 个答案:

答案 0 :(得分:1)

  

我希望它只显示1篇博文。我怎么能在while循环中做到这一点?感谢

您是否了解while循环专门用于显示多个帖子?

正如其他用户指出的那样,您可以修改查询以仅选择一个帖子。但是,如果您正在使用主要查询或无法更改的其他子查询,要显示单个帖子,则不需要while循环

query_posts('cat=1');
if (have_posts()) {
  the_post();
  the_title();
}
else {
  echo 'sorry no posts';
}

如果您因任何原因必须保持while循环,则可以在显示第一个之后break

while (have_posts()) {
  the_post();
  the_title();
  break;
}

最后一句话是关于您在if之前使用while。这毫无意义

<?php if (have_posts()): while (have_posts()): the_post() ?>
  ...
<?php endwhile; endif; ?>

可以改写为

<?php while (have_posts()): the_post() ?>
  ...
<?php endwhile ?>

答案 1 :(得分:1)

更新query_posts以使用posts_per_page参数:

query_posts('cat=1&posts_per_page=1');

一次只能抓一个帖子。

https://developer.wordpress.org/reference/functions/query_posts/#more-information