置顶文章只显示一次
闲来没事的时候仔细查看站内的内容和布局,发现在一个基本的循环中,置顶文章除了在第一页的顶部出现外,还在分页内重复出现,导致失去了置顶文章的意义,把心一横,重新编写吧!灵感来源于互联网,后来发现有一篇文章和我实现的一摸一样,代码比我的优秀,测试了一下也可行,就分享网上找来的代码吧:
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,刷新页面,只在分页第一页显示置顶文章!
Last Updated On Mar 17, 2024 At 11:15:48 PM