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 这个参数了,坏处就是有时候要多一次查询操作。
本文作者为鲍成龙,转载请注明。