修改前:
修改后:
后台设置:
教程开始:
代码放入:function.php
function modify_pre_get_posts($query) {
if ($query->is_home() && $query->is_main_query()) {
$sticky_posts = get_option('sticky_posts');
$sticky_count = count($sticky_posts);
$posts_per_page = get_option('posts_per_page');
if (!$query->is_paged()) {
if ($sticky_count > 0) {
$query->set('posts_per_page', $posts_per_page - $sticky_count);
}
} else {
if (!empty($sticky_posts)) {
$query->set('post__not_in', $sticky_posts);
$offset = ( $query->query_vars['paged'] - 1 ) * $posts_per_page - count($sticky_posts);
$query->set('offset', $offset);
}
}
}
}
add_action('pre_get_posts', 'modify_pre_get_posts');
function adjust_pagination() {
if (is_home()) {
global $wp_query;
$sticky_posts = get_option('sticky_posts');
$sticky_count = count($sticky_posts);
$posts_per_page = get_option('posts_per_page');
// 获取非置顶文章总数
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'post__not_in' => $sticky_posts,
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
);
$non_sticky_query = new WP_Query($args);
$non_sticky_count = $non_sticky_query->post_count;
// 第1页显示的普通文章数
$first_page_posts = $posts_per_page - $sticky_count;
// 剩余普通文章数
$remaining_posts = $non_sticky_count - $first_page_posts;
// 计算总页数:第1页 + 剩余页数
if ($remaining_posts > 0) {
$total_pages = 1 + ceil($remaining_posts / $posts_per_page);
} else {
$total_pages = 1;
}
$wp_query->max_num_pages = $total_pages;
}
}
add_action('wp', 'adjust_pagination');



