WordPress 技巧:在 WP_Query 使用 post__in 的时候注意要 ignore_sticky_posts
今天和同事在使用 WP_Query 的 post__in 参数的时候:
$like_query = new WP_Query(array(
'post_type' => array('post','event'),
'post__in' => array(138,139),
'orderby' => 'post__in',
'posts_per_page'=> -1
) );
但是返回的结果总是超过这个 138, 139 这两篇,甚是奇怪。后面仔细查看文档,才发现有如下这段话:
ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use ignore_sticky_posts.
原来如此,我又正好使用了 sticky posts,置顶文章,所以,哎,调试了整整好几个小时,都把 WP 源代码翻烂了。
所以最终的代码应该是:
$like_query = new WP_Query(array(
'post_type' => array('post','event'),
'post__in' => array(138,139),
'orderby' => 'post__in',
'posts_per_page' => -1,
'ignore_sticky_posts' => 1
) );