菜鸟站长
个人博客主题模板、应用插件、功能开发技术资源聚合分享网站

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

发布者:菜鸟站长  发布日期:2023-12-29  更新日期:2023-12-29  人气指数:1031

一般制作的 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置顶文章的策略总结完毕。

本文检索关键词:WordPress教程 , 置顶文章

菜鸟站长推荐教程



添加新评论 »

icon_mrgreen.pngicon_neutral.pngicon_twisted.pngicon_arrow.pngicon_eek.pngicon_smile.pngicon_confused.pngicon_cool.pngicon_evil.pngicon_biggrin.pngicon_idea.pngicon_redface.pngicon_razz.pngicon_rolleyes.pngicon_wink.pngicon_cry.pngicon_surprised.pngicon_lol.pngicon_mad.pngicon_sad.pngicon_exclaim.pngicon_question.png