Php WordPress停止获取帖子的循环

Php WordPress停止获取帖子的循环,php,mysql,wordpress,loops,while-loop,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个博客

这是我从类别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循环中做到这一点?谢谢

我希望它只显示1个博客文章。我如何在while循环中做到这一点?谢谢

您是否了解
while
循环专门用于显示多篇文章

正如另一位用户所指出的,您可以修改查询以仅选择一篇文章。但是,如果您使用的是无法更改的主查询或另一个子查询,要显示单个帖子,则不需要
while
循环

query_posts('cat=1');
if (have_posts()) {
  the_post();
  the_title();
}
else {
  echo 'sorry no posts';
}
如果出于任何原因必须保持
while
循环,则可以在显示第一个循环后
中断

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

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

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

...
可以重写为

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

...

更新
query\u posts
以使用
posts\u per\u page
参数:

query_posts('cat=1&posts_per_page=1');
一次只能抓住一个帖子


我不同意在while之前使用if语句毫无意义。可能只是作为if语句,但and if语句是显示“未找到帖子”消息的唯一方式。@Kenyon这不是问题中的代码。我对现行守则作了评论;不多也不少。解决您提出的问题可以通过多种方式完成。