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

温馨提示: 本文最后更新于2024-09-10 19:35:52,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系 苏晨博客网

最新教程

功能介绍

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

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

未设置效果图

WordPress修改置顶文章加入到显示文章数量内-苏晨博客网

设置后效果图

WordPress修改置顶文章加入到显示文章数量内-苏晨博客网

代码添加方法

将下面代码放置于functions.php内,子比主题推荐放在func.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;
        $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');
© 版权声明
THE END
喜欢就支持一下吧
评论 抢沙发

请登录后发表评论

    暂无评论内容