You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress首页如何展示全部文章且排除sticky置顶文章

解决方案

方法1:使用pre_get_posts钩子修改主查询(推荐)

该方案从查询层面直接排除置顶文章,不影响分页逻辑,性能最优。只需将以下代码添加到当前主题的functions.php文件中即可,原有首页循环代码无需任何修改:

add_action( 'pre_get_posts', 'exclude_sticky_posts_from_home' );
function exclude_sticky_posts_from_home( $query ) {
    // 仅在首页主查询生效
    if ( $query->is_home() && $query->is_main_query() ) {
        // 排除所有置顶文章
        $query->set( 'ignore_sticky_posts', 1 );
        $sticky_posts = get_option( 'sticky_posts' );
        if ( ! empty( $sticky_posts ) ) {
            $query->set( 'post__not_in', $sticky_posts );
        }
    }
}

方法2:在现有循环内判断过滤

如果不想修改主题functions.php文件,也可以直接在原有循环里增加置顶判断,仅输出非置顶文章,修改后的代码如下:

if ( have_posts() ) :
?>
    <div class="row my-4">
    <?php
        while ( have_posts() ) :
            the_post();
            // 跳过置顶文章
            if ( is_sticky() ) {
                continue;
            }
            /**
             * Include the Post-Format-specific template for the content.
             * If you want to overload this in a child theme then include a file
             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
             */
            get_template_part( 'content', 'index' ); // Post format: content-index.php
        endwhile;
    ?>
    </div>
<?php
endif;

wp_reset_postdata();

注意:该方法仅在渲染时跳过置顶文章,不会修改主查询的分页计数,可能出现首页显示的文章数量比后台设置值少的情况,更推荐使用第一种方案。

内容的提问来源于stack exchange,提问作者Kamarat AbdelSalam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:48:03