The next version of Index is here! To celebrate, take 25% off your purchase with the code 25OFF. Learn more
Index Logo

How to amend WordPress REST endpoint queries

WordPress offers very powerful filters to change database queries in PHP. Did you know they offer the same thing for the REST API? Learn how to use these filters below.

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

Try Index for free Index upgrades all of your WordPress post types. Try the demo and see for yourself. Try the demo no credit card required

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.

Get started with Index

See for yourself why Index is the most intuitive, beautiful interface for managing your WordPress content.