这是基本循环
<?php while (have_posts()) : the_post(); ?>
我想在搜索结果页面上显示 20 条帖子。我知道我们可以更改管理面板选项上的值,但它会更改所有内容,即索引页面和存档页面等。我需要以不同的方式使用它们。
很好的参考:http://codex.wordpress.org/The_Loop
在调用 while 语句之前,您需要查询帖子。所以:
<?php query_posts('posts_per_page=20'); ?>
<?php while (have_posts()) : the_post(); ?>
<!-- Do stuff... -->
<?php endwhile;?>
编辑:抱歉分页,试试这个:
<?php
global $query_string;
query_posts ('posts_per_page=20');
if (have_posts()) : while (have_posts()) : the_post();
?>
<!-- Do stuff -->
<?php endwhile; ?>
<!-- pagination links go here -->
<? endif; ?>
我找到了这个解决方案,它对我有用。
global $wp_query;
$args = array_merge( $wp_query->query_vars, ['posts_per_page' => 20 ] );
query_posts( $args );
if(have_posts()){
while(have_posts()) {
the_post();
//Your code here ...
}
}
您可以通过 $wp_query 对象限制每个循环的帖子数量。 例如,它需要多个参数:
<?php
$args = array('posts_per_page' => 2, 'post_type' => 'type of post goes here');
$query = new WP_Query( $args );
while( $query->have_posts()) : $query->the_post();
<!-- DO stuff here-->
?>
有关 wp_query 对象的更多信息 此处->
添加 'paged' => $paged 分页就可以了!
<?php
$args = array('posts_per_page' => 2, 'paged' => $paged);
$query = new WP_Query( $args );
while( $query->have_posts()) : $query->the_post();
<!-- DO stuff here-->
?>
模板内新查询的答案将无法与自定义帖子类型一起正常工作。
但是文档提供了挂钩任何查询的功能,检查它是否是主查询,并在执行之前对其进行修改。这可以在模板函数内完成:
function my_post_queries( $query ) {
// do not alter the query on wp-admin pages and only alter it if it's the main query
if (!is_admin() && $query->is_main_query()) {
// alter the query for the home and category pages
if(is_home()){
$query->set('posts_per_page', 3);
}
if(is_category()){
$query->set('posts_per_page', 3);
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );
在调用 if 语句之前,您需要查询帖子。
此功能适用于存档、自定义帖子类型等。
global $query_string;
query_posts( $query_string . '&posts_per_page=12' );
if ( have_posts() ) :