WP REST API core major changes

As of WordPress 4.7 now we have the following filter to hook to:

$args = apply_filters( "rest_{$this->post_type}_query", $args, $request );

So if you would like to perform a request like:

http://yoursite.com/wp-json/wp/v2/posts?meta_key=your_key&meta_value=your_value&per_page=10

OR

http://yoursite.com/wp-json/wp/v2/posts?meta_query[0][key]=your_key&meta_query[0][value]=your_value&per_page=10

you can do it through the following piece of code (within your functions.php):


/**
 * This function will allow custom parameters within API request URL.
 *
 * @link    https://codex.wordpress.org/Class_Reference/WP_Query
 * @see     Wp-includes/Rest-api/Endpoints/Class-wp-rest-posts-controller.php
 * @param   array   $args       Contains by default pre written params.
 * @param   array   $request    Contains params values passed through URL request.
 * @return  array   $args       New array with added custom params and its values.
 */
public function posts_allow_custom_request_params( $args, $request ) {

    $args += array(
        'meta_key' => $request['meta_key'],
        'meta_value' => $request['meta_value'],
        'meta_query' => $request['meta_query'],
    );

    return $args;

}

add_filter( 'rest_post_query', 'posts_allow_custom_request_params', 99, 2 );

Note that I’m supposing you are requesting posts from the post type ‘post’.

You can add as many parameters as you want provided that your array indexes match the correct parameters accepted by WP_Query class. And if you look through my comments along the code you might find something useful to look into.

By the way here are some parameters you have by default that you can use within your query string:


'author'            => 'author__in',
'author_exclude'    => 'author__not_in',
'exclude'           => 'post__not_in',
'include'           => 'post__in',
'menu_order'        => 'menu_order',
'offset'            => 'offset',
'order'             => 'order',
'orderby'           => 'orderby',
'page'              => 'paged',
'parent'            => 'post_parent__in',
'parent_exclude'    => 'post_parent__not_in',
'search'            => 's',
'slug'              => 'post_name__in',
'status'            => 'post_status',
'per_page'          => 'posts_per_page',

Considering the WP_Query class, ‘page’ is equivalent to ‘paged’, ‘status’ is equivalent to ‘post_status’, so on…

Using the above parameters we’d end up with something like:

http://yoursite.com/wp-json/wp/v2/posts?offset=2&status=future

Hope this helps. And be optimistic believing that if they did it it’s for the best, always!

Leave a Comment