修改前:

修改后:

后台设置:

教程开始:

[hidecontent type=”reply” desc=”隐藏内容:评论后查看”]

代码放入: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');

 

[/hidecontent]

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。