Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Search post by post meta with rest api.
* Add meta fields support in rest API for post type `Post`
* This function will allow custom parameters within API request URL. Add post meta support for post type `Post`.
* > How to use?
* > E.g. Get posts which post meta `already-visited` value is `true`.
* Request like:
* @since 1.0.0
* @link
* @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.
if( ! function_exists( 'post_meta_request_params' ) ) :
function post_meta_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', 'post_meta_request_params', 99, 2 );
// add_filter( 'rest_page_query', 'post_meta_request_params', 99, 2 ); // Add support for `page`
// add_filter( 'rest_my-custom-post_query', 'post_meta_request_params', 99, 2 ); // Add support for `my-custom-post`

This comment has been minimized.

Copy link

wtfmejt commented Nov 14, 2019

How could I add multiple custom fields to it? Let's say I have two custom fields one named country and the other city and I want to find posts that match the custom fields country=spain and city=madrid?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.