【问题标题】:WordPress stop loop from getting postsWordPress停止循环获取帖子
【发布时间】:2017-04-30 09:16:15
【问题描述】:

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

【问题讨论】:

    标签: php mysql wordpress loops while-loop


    【解决方案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;
    }
    

    最后一点是关于您在while 之前使用if。没有意义

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

    可以改写为

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

    【讨论】:

    • 我不同意在 while 之前有 if 语句没有意义。可能仅作为 if 语句,但 if 语句是显示“未找到帖子”消息的唯一方法。
    • @Kenyon 好吧,这不是有问题的代码。我为现有代码提供了注释;不多不少。可以通过多种方式解决您提出的问题。
    【解决方案2】:

    更新query_posts 以使用posts_per_page 参数:

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

    一次只能抓取一个帖子。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 2010-11-26
      • 2016-03-05
      • 2014-11-13
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多