插件与教程

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

authorCrazy uncle publish2022-09-12 update2022-09-12 view913

排除置顶

一般制作的wordpress主题的首页是应该出现置顶文章的,毕竟置顶是有意义的,但如果在设计首页的时候,为置顶文章设计了专属的位置展示后,此时再在主循环里再输出置顶文章就有点重复输出的感觉了,

一般通过给主循环设定输出逻辑,都是使用query_posts($args);但会出现翻页的问题,翻到第二页还是显示的第一页的文章列表,所以,才有了今天的教程,

//首页主循环中排除置顶文章
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');

将以上代码插入 functions.php,如果要排除其它页面的,就把代码中的is_home()改一下即可。

WordPress只输出置顶文章

那么,既然上面说了,将对置顶文章做独立的位置展示,那么又如何WordPress只输出置顶文章呢?

<?php
$args = array(
    'posts_per_page' => -1,
    'post__in'  => get_option( 'sticky_posts' )
);
$sticky_posts = new WP_Query( $args );
while ( $sticky_posts->have_posts() ) : $sticky_posts->the_post();?>
循环内容
<?php endwhile; wp_reset_query();?>

通过以上代码就会输出整站所有的置顶文章。对,是所有置顶,如果整站里有二三十个置顶文章,显然又不是我们想要的输出结果。

控制输出数量

但如果要对输出的文章数量做控制,则需要用到以下代码

<?php
$sticky = get_option( 'sticky_posts' );
rsort( $sticky );
$sticky = array_slice( $sticky, 0, 5 );
query_posts( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );
while ( have_posts() ) : the_post(); ?>

<?php endwhile; wp_reset_query();?>

代码里的5,就是输出所有置顶文章里的最新5篇

到此,独立展示wordpress置顶文章的策略总结完毕。

有用(4)

这些你同样感兴趣

满足你在每个阶段使用模板的需求,帮助你高效完成工作及任务