WordPress query parameters and developer experience
No matter how we implement our WordPress plugins, if we expect other (theme) developers to interact with our code, we should not expect more knowledge than it's assumed by WordPress core.
I like the fact that WordPress codebase is approachable and expressive, that you can do complex database queries without knowing SQL or the internals of the query class.
One way to keep the barrier low, maintain expressivity, and hide complexity is to introduce custom query parameters.
Let's say you provide a way to manage events. Instead of forcing theme developers to interact with your classes and methods, you can let them retrieve events using something that is already familiar to them:
$events = get_posts(
[
'post_type' => 'event',
'event' => [
'location' => [
'Chicago',
'Boston',
],
'after' => '2020-08-15',
],
]
);
Internally then you can map this to a complex meta_query
and date_query
or even pass to your repository class.
Or you can extend existing paramaters with custom values:
$popularPosts = get_posts(
[
'post_type' => 'post',
'orderby' => 'popular',
]
);
Using the pre_get_post
action, you can check the value of orderby
and set the necessary query parameters. In general, it's a good idea to save others from knowing things that are not immediately important.
add_action(
'pre_get_posts',
static function (WP_Query $query) {
if ($query->get('orderby') !== 'popular') {
return;
}
if ($query->get('post_type') !== 'post') {
return;
}
$query->set('orderby', 'meta_value_num post_date');
$query->set('meta_key', '_your_meta_key_for_ranking');
}
);
Small details like these make a difference in the developer experience (DX).