请注意WP_Query
类实例,如$homePageArticles
在你的情况下,你应该通过max_num_pages
类实例的属性paginate_links()
:
paginate_links( array(
\'total\' => $homePageArticles->max_num_pages,
) )
但是,仅此一点不适用于自定义偏移
breaks the pagination, 因此,例如,您遇到了以下问题:
它只是在每个页面上显示相同的帖子
但它可以被修复,而且非常简单:
根据当前页码计算偏移量,并将偏移量传递给WP_Query
:
// Current page number.
$paged = max( 1, get_query_var( \'paged\' ) );
$per_page = 18; // posts per page
$offset_start = 9; // initial offset
$offset = $paged ? ( $paged - 1 ) * $per_page + $offset_start : $offset_start;
$homePageArticles = new WP_Query( array(
\'posts_per_page\' => $per_page,
\'offset\' => $offset,
\'post_type\' => \'articles\',
// No need to set \'paged\'.
) );
重新计算
max_num_pages
属性并将其传递给
paginate_links()
:
$homePageArticles->found_posts = max( 0, $homePageArticles->found_posts - $offset_start )
$homePageArticles->max_num_pages = ceil( $homePageArticles->found_posts / $per_page );
while ( $homePageArticles->have_posts() ) ...
echo paginate_links( array(
\'current\' => $paged,
\'total\' => $homePageArticles->max_num_pages,
...
) );
但是,如果您在存档模板中进行自定义WP查询,例如。archive-articles.php
(archive-<post type>
.php)
那么您应该忘记自定义WP查询。相反,使用pre_get_posts
hook 要筛选主要WP查询参数(设置自定义偏移量),请使用found_posts
hook 确保我们有正确的max_num_pages
值,然后在主查询中循环浏览帖子。
主题函数文件中:
function my_pre_get_posts( $query ) {
if ( ! is_admin() && $query->is_main_query() &&
is_post_type_archive( \'articles\' )
) {
$query->set( \'offset_start\', 9 );
$query->set( \'posts_per_page\', 18 );
}
if ( $offset = $query->get( \'offset_start\' ) ) {
$per_page = absint( $query->get( \'posts_per_page\' ) );
$per_page = $per_page ? $per_page : max( 1, get_option( \'posts_per_page\' ) );
$paged = max( 1, get_query_var( \'paged\' ) );
$query->set( \'offset\', ( $paged - 1 ) * $per_page + $offset );
}
}
add_action( \'pre_get_posts\', \'my_pre_get_posts\' );
function my_found_posts( $found_posts, $query ) {
if ( $offset = $query->get( \'offset_start\' ) ) {
$found_posts = max( 0, $found_posts - $offset );
}
return $found_posts;
}
add_filter( \'found_posts\', \'my_found_posts\', 10, 2 );
然后在存档模板中:// No need for the "new WP_Query()".
while ( have_posts() ) : the_post();
... your code.
endwhile;
// No need to set \'current\' or \'total\'.
echo paginate_links( array(
\'prev_text\' => \'NEWER\',
\'next_text\' => \'OLDER\',
...
) );
实际上,使用上面#1中的自定义函数,您只需使用offset_start
arg带任何WP_Query
实例:// Current page number.
$paged = max( 1, get_query_var( \'paged\' ) );
$homePageArticles = new WP_Query( array(
\'posts_per_page\' => 18,
\'offset_start\' => 9, // <- set this
\'post_type\' => \'articles\',
// No need to set \'paged\' or \'offset\'.
) );
while ( $homePageArticles->have_posts() ) ...
echo paginate_links( array(
\'current\' => $paged,
\'total\' => $homePageArticles->max_num_pages,
...
) );