WordPress函数:WP_Query 查询置顶文章的方法和建议

追格官方小助手/ 2022年07月10日/ WordPress/ 浏览 1998

WordPress有关文章置顶的问题,经常让新手迷惑。


其关键就在于,WP_Query 的 ignore_sticky_posts 参数。这个参数为false,则会在查询结果的头部,附带所有的置顶文章。ignore_sticky_posts 默认值为 false。


在开发中,最好把 ignore_sticky_posts 总是设置为 true。如果需要置顶文章,则使用下面的方法:


$args = array(
    'post__in'            => get_option( 'sticky_posts' ),
    'ignore_sticky_posts' => 1,
);
$query = new WP_Query( $args );


如果,想查询分类6下的文章,但是想在查询结果中排除分类6中已置顶的文章(置顶文章在其他地方展示),可以参考以下代码:


$sticky = get_option( 'sticky_posts' );
$args = array(
    'cat'                 => 6,
    'ignore_sticky_posts' => 1,
    'post__not_in'        => $sticky,
);
$query = new WP_Query( $args );


这样做的好处就是脑子里不用老想 ignore_sticky_posts 这个参数了,坏处就是有时候要多一次查询操作。


之前关于WordPress置顶的文章:

1. WordPress如何获取置顶文章
2. WordPress中如何判断文章是否置顶
3. WordPress中如何设置文章置顶
4. WordPress中如何给文章前面加上置顶小图标

WP_Query 的基础用法可以参考文章:WP_Query 的基础用法简介

发表评论

暂无评论,抢个沙发...

客服 工单