下面是一个带有分页的二次循环的工作示例,它可以用于单发帖子。WP_Query
通常是比query_posts()
. 您的永久链接设置不应成为此处的一个因素。
<?php
$my_query = new WP_Query( [
\'posts_per_page\' => 3,
\'paged\' => ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1,
\'post_type\' => \'post\',
] );
?>
<?php if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; ?>
<nav id="nav-posts">
<?php
$big = 999999999; // need an unlikely integer
echo paginate_links( [
\'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
\'format\' => \'?paged=%#%\',
\'current\' => max( 1, get_query_var(\'paged\') ),
\'total\' => $my_query->max_num_pages,
\'before_page_number\' => sprintf( \'<span class="screen-reader-text">%1$s</span>\', __( \'Page\', \'mytextdomain\' ) )
] );
?>
</nav>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
在单个帖子上使用第二个循环进行分页有点棘手。
gmazzap 发布了全面的解释和解决方案
here. 下面的代码是从该解决方案中复制的,是允许分页与上面发布的辅助循环一起工作所必需的。
add_action( \'template_redirect\', \'wpse247933_single_post_second_loop_pagingation_fix\', 0 );
// on priority 0 to remove \'redirect_canonical\' added with priority 10
function wpse247933_single_post_second_loop_pagingation_fix() {
if ( is_singular( \'post\' ) ) {
global $wp_query;
$page = ( int ) $wp_query->get( \'page\' );
if ( $page > 1 ) {
// convert \'page\' to \'paged\'
$query->set( \'page\', 1 );
$query->set( \'paged\', $page );
}
// prevent redirect
remove_action( \'template_redirect\', \'redirect_canonical\' );
}
}