AI摘要

本文提供一段代码,解决WordPress首页置顶文章导致实际显示数量超出后台设置的问题,将置顶数计入首页文章总数内(仅首页生效),并修复了分页总数错误等bug,适用于子比主题美化。

功能介绍

WordPress默认第一页的置顶文章不在数量内,那么如果你设置首页文章数量为10的话,你有四篇置顶文章,那么他就会显示14篇文章,这样让首页的文章不美观,我们可以增加一个代码来控制文章数量。

代码仅第一页文章有效,第二页以后和用户中心的文章数量是你后台设置的文章数量(不受置顶文章的影响)

效果图

修复bug

  • 修复首页总页数显示错误
  • 修复分类等其他显示置顶的页面没有实现效果

代码

[hidecontent type="reply"]

将下面代码放置于主题 functions.php 内,子比主题推荐放在func.php文件不受主题更新迭代影响

function modify_pre_get_posts($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() {
        global $wp_query;
        $total_posts = $wp_query->found_posts;
        $sticky_posts = get_option('sticky_posts');
        $sticky_count = count($sticky_posts);
        $posts_per_page = get_option('posts_per_page');
        $total_posts -= $sticky_count;
        $total_pages = ceil($total_posts / $posts_per_page);
        $wp_query->max_num_pages = $total_pages;
}
add_action('wp', 'adjust_pagination');
[/hidecontent]