2024 年 5 月 10 日 我的频道
置顶文章只显示一次
  • 2022
  • Sunny

闲来没事的时候仔细查看站内的内容和布局,发现在一个基本的循环中,置顶文章除了在第一页的顶部出现外,还在分页内重复出现,导致失去了置顶文章的意义,把心一横,重新编写吧!灵感来源于互联网,后来发现有一篇文章和我实现的一摸一样,代码比我的优秀,测试了一下也可行,就分享网上找来的代码吧:

add_action( 'pre_get_posts', 'show_sticky_posts_on_first_page' );
function show_sticky_posts_on_first_page( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_home() && $query->is_paged() ) {
        $paged = $query->get( 'paged' );
        if ( $paged == 1 ) {
            $sticky_posts = get_option( 'sticky_posts' );
            if ( ! empty( $sticky_posts ) ) {
                $query->set( 'post__in', $sticky_posts );
                $query->set( 'ignore_sticky_posts', false );
            }
        } else {
            $query->set( 'post__not_in', get_option( 'sticky_posts' ) );
            $query->set( 'ignore_sticky_posts', true );
        }
    }
}

把代码放到 ZFunctions.php,刷新页面,只在分页第一页显示置顶文章!

STUDY
780
0

Author Box

名字:Sunny
注册:Jan 30, 2021
简介:技术菜鸟,拷贝、黏贴代码中 ……

Comment Box

0 0 投票数
Article Rating
订阅评论
提醒
guest

0 评论
内联反馈
查看所有评论