Getting Started
The rest_{$post_type}_query
filter helps you ammend the query parameters of any REST enabled post type, plus attachments. The filter function takes two parameters:
$args
: the arguments array that will passed on to the WordPress query$request
: the REST request, including any parameters passed in by the URL
The $args
array is formatted the same as a WP_Query
args array (because it will eventually be used in one. This means you can augment the $args
array with any valid options that WP_Query
accepts
Example
Let’s say we want to support passing in meta_query and taxonomy_query values when querying posts. We’re going to assume the passed in values are JSON encoded meta/tax_query
values, so all we need to do is the following:
<?php
add_filter('rest_post_query', function($args, $request) {
if(isset($request['meta_query'])) {
$meta_query = json_decode($request['meta_query'], true);
if($meta_query !== null) {
$args['meta_query'] = $meta_query;
}
}
if(isset($request['tax_query'])) {
$tax_query = json_decode($request['tax_query'], true);
if($meta_query !== null) {
$args['tax_query'] = $tax_query;
}
}
});
First we check if the $request
parameter includes meta/tax_query
options. In this case we’ve passed in fully JSON encoded queries. Next, we ensure decoding works and if so, we add meta/tax_query
values to our $args
array.
Note: The true
parameter in json_decode
creates an associative array (versus an object), which is required to be valid in a WP_Query
instance.