使用查询循环遍历 Wordpress 帖子 + have_posts() 只有 returns 其中的一小部分
Looping through Wordpress posts using a query + have_posts() only returns a fraction of them
我正在尝试创建自定义 HTML 站点地图。我正在使用以下 PHP 代码来检索网站中的所有帖子:
$args = array(
'post_type' => 'post'
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
?>
<a href=" <?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
}
}
wp_reset_postdata();
出于某种原因,上面的代码只打印了最近 10 篇文章的链接。我的网站上有 30 多个帖子。由于我对PHP不是很满意,所以上面的代码有什么问题吗?有没有不同的方法可以尝试实现相同的输出?谢谢。
为了在一个页面上显示更多的帖子,也可以调整常规的 Wordpress 设置,在 Settings > Reading > Blog pages show max. XX pages
下的后端(确切的术语可能有点不同,我通常使用另一种语言)
或者,您可以在查询参数($args
数组)中添加相应的参数,例如 'posts_per_page' => 30,
.
您需要在查询中设置 posts_per_page
参数。 -1 等于所有帖子。
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$post_query = new WP_Query($args);
虽然两个答案都是正确的。让我们看看您可能想要先做一个再做另一个的一些原因。
正在更改设置 > 阅读 > 博客页面最多显示。
这可能会影响网站上没有 posts_per_page 设置的其他查询。在与其他插件交互时,这有可能产生隐藏的和意想不到的后果。
使用
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$post_query = new WP_Query($args);
有可能创建一个无限滚动的页面,具体取决于它的使用方式。 300 个帖子?没问题,他们只是被转储到页面上。
您可能需要考虑根据可能的设计将它们限制为用户友好的内容并使用分页来处理额外的内容。
我正在尝试创建自定义 HTML 站点地图。我正在使用以下 PHP 代码来检索网站中的所有帖子:
$args = array(
'post_type' => 'post'
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
?>
<a href=" <?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
}
}
wp_reset_postdata();
出于某种原因,上面的代码只打印了最近 10 篇文章的链接。我的网站上有 30 多个帖子。由于我对PHP不是很满意,所以上面的代码有什么问题吗?有没有不同的方法可以尝试实现相同的输出?谢谢。
为了在一个页面上显示更多的帖子,也可以调整常规的 Wordpress 设置,在 Settings > Reading > Blog pages show max. XX pages
下的后端(确切的术语可能有点不同,我通常使用另一种语言)
或者,您可以在查询参数($args
数组)中添加相应的参数,例如 'posts_per_page' => 30,
.
您需要在查询中设置 posts_per_page
参数。 -1 等于所有帖子。
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$post_query = new WP_Query($args);
虽然两个答案都是正确的。让我们看看您可能想要先做一个再做另一个的一些原因。
正在更改设置 > 阅读 > 博客页面最多显示。
这可能会影响网站上没有 posts_per_page 设置的其他查询。在与其他插件交互时,这有可能产生隐藏的和意想不到的后果。
使用
$args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$post_query = new WP_Query($args);
有可能创建一个无限滚动的页面,具体取决于它的使用方式。 300 个帖子?没问题,他们只是被转储到页面上。
您可能需要考虑根据可能的设计将它们限制为用户友好的内容并使用分页来处理额外的内容。