增强 WordPress 查询能力,给 WP_Query 增加置顶文章参数(sticky_posts)
我们知道 WordPress 有置顶功能,可以在后台将一些文章置顶到列表前面:

默认这个置顶功能只支持 WordPress 首页,所以我加强了一下,发布了 WPJAM「文章置顶」WordPress 插件,支持置顶文章排序和分类文章置顶。
但是插件还是需要在特定位置设置置顶的文章,如下图:

那么我们在 WordPress 开发的时候,使用 WP_Query
进行查询的时候,能否传递个参数就实现任意的文章列表,除了默认的查询的文章之后,还能包含这个置顶参数指定的文章,这样灵活度和定制能力就强了很多,说干就干,然后这个参数也叫做 stick_posts
。
add_filter('posts_results', function($posts, $query){
$q = &$query->query_vars;
$sticky_posts = array_diff(wp_parse_id_list(wpjam_pull($q, 'sticky_posts') ?: []), $q['post__not_in']);
if($sticky_posts && ($stickies = get_posts([
'orderby' => 'post__in',
'post__in' => $sticky_posts,
'post_type' => $q['post_type'] ?: 'post',
'post_status' => 'publish',
'posts_per_page' => count($sticky_posts),
'suppress_filters' => $q['suppress_filters'],
'cache_results' => $q['cache_results'],
'update_post_meta_cache' => $q['update_post_meta_cache'],
'update_post_term_cache' => $q['update_post_term_cache'],
'lazy_load_term_meta' => $q['lazy_load_term_meta'],
]))){
$q['sticky_posts'] = array_column($stickies, 'ID');
return array_merge($stickies, array_filter($posts, fn($post)=> !in_array($post->ID, $q['sticky_posts'], true)));
}
return $posts;
}, 1, 2);
上面这段代码的意思就是 WP_Query
查询参数中如果有 stick_posts
这个参数,就在 posts_results
filter 中获取这个参数,然后通过它获取相应的文章,插入到文章列表的前面。
就这么简单,使用的时候也非常简单:
$query = new WP_Query(['post_type'=>'product', 'sticky_posts'=>[123, 456]]);
如上面列表,就是在商品列表前面把 ID 为 123 和 456 的商品放到最新商品列表的前面,最后新版的 WPJAM Basic 已经集成上面 hook 代码,如果你是开发者,只需要在 WP_Query
进行自定义查询的时候,直接使用 stick_posts
即可。
下一步,我也会基于这个参数对 WPJAM「文章置顶」 插件进行优化和改进。