Skip to content
This repository has been archived by the owner on Sep 24, 2018. It is now read-only.

How should a user retrieve all posts that have a meta key #1599

Closed
CGeorges opened this issue Sep 25, 2015 · 7 comments
Closed

How should a user retrieve all posts that have a meta key #1599

CGeorges opened this issue Sep 25, 2015 · 7 comments

Comments

@CGeorges
Copy link

I want to retrieve all posts that have a certain meta key.

Eg: filter[meta_key] = test
filter[meta_value] = on

Passing this filter to /wp-json/posts returns all posts. What should I do in order to achieve this result ?

@Toddses
Copy link
Contributor

Toddses commented Sep 26, 2015

These fields aren't filterable by default. They can be added via the rest_query_vars filter:

add_filter( 'rest_query_vars', 'flux_allow_meta_query' );
function flux_allow_meta_query( $valid_vars )
{
    $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) );
    return $valid_vars;
}

That should open up the filter for the wp-json/wp/v2/posts endpoint, like so wp-json/wp/v2/posts?filter[meta_key]=test&filter[meta_value]=on

@CGeorges
Copy link
Author

Thank you! Is for v1 the same process ? I forgot to mention I was using v1 sorry!

@equatorapps
Copy link

This works for a single meta key, but how do we use this filter to limit the results based on multiple meta keys?

@danielbachhuber
Copy link
Member

how do we use this filter to limit the results based on multiple meta keys?

You'll need to write some custom code for this, as it isn't supported out of the box.

@trevanhetzel
Copy link

@danielbachhuber Would you happen to have any resources to link to about writing a custom filter (if possible)? Like @equatorapps, I'd also like to limit results based on multiple meta keys.

With v1 I was doing it like this and it seemed to work fine:

&filter[meta_value][month]=12&[meta_value][year]=2015

Thanks!

@msankar1991
Copy link

msankar1991 commented May 12, 2016

How to write some custom code for two or more custom meta fields filter using with REST WP API.Can you give me the example..

example: filter[meta_key]=beds&filter[meta_value]=4&filter[meta_compare]=>=&filter[meta_key]=basins&filter[meta_value]=4&filter[meta_compare]=>=

And also how to filtering custom post type on a combination of custom taxonomies and custom meta fields?

@benlk
Copy link

benlk commented Feb 26, 2018

Leaving a note here for future spelunkers:

The rest_query_vars filter no longer exists in WordPress. Take a look at https://developer.wordpress.org/reference/hooks/rest_this-post_type_collection_params/ and https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants