gpt4 book ai didi

php - WordPress停止循环获取帖子

转载 作者:行者123 更新时间:2023-11-29 06:06:37 27 4
gpt4 key购买 nike

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

最佳答案

i want it to only display 1 blog post. how can i do that in the while loop? thanks

你明白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 ?>

关于php - WordPress停止循环获取帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com