置顶文章加入到显示文章数量内

2025-10-17 0 522

修改前:

置顶文章加入到显示文章数量内

修改后:

置顶文章加入到显示文章数量内

后台设置:

置顶文章加入到显示文章数量内

教程开始:

[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]

 

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

轩玮博客 WordPress 置顶文章加入到显示文章数量内 http://blog.xuwbk.com/739.html

常见问题

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务