WordPress首页主循环中排除置顶文章的代码

出于网站的开发需求,在首页主循环外的位置单独调用了网站的置顶文章,由于不想在首页出现两块相同置顶文章的列表,所以要排除主循环中最新文章前面的置顶文章。

WordPress首页主循环中排除置顶文章的代码

以前通过 query_posts()实现排除置顶文章的教程,但是使用 query_posts()很容易引起文章列表的分页问题,因此并不是很建议使用,这里推荐使用下面的代码。

把下面的代码添加到当前主题的 functions.php 文件,保存即可

function exclude_sticky_posts($query){
    if ( is_admin() || ! $query->is_main_query() )
	    return;
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'ignore_sticky_posts', 1 );
    }
}  
add_action('pre_get_posts','exclude_sticky_posts');

如果要排除其它页面的,就把代码中的 is_home()改一下即可。

(0)
上一篇 2022-04-02 15:48
下一篇 2022-04-06 15:42

相关推荐