1

So I know that I can call:

$response = wp_remote_get(
    'https://www.example.com/wp-json/wp/v2/posts'
);

To get all the posts from a specific website using the Rest API Endpoint.


I also know that we can pass in the parameters to exclude tags and categories, such as:

https://www.example.com/wp-json/native/v1/posts?exclude_categories=42

Based on this: https://developer.wordpress.org/rest-api/reference/posts/#list-posts


Is there a way that I can exclude specific post_meta posts from showing in the Rest API?

So let that I want to do: https://www.example.com/wp-json/native/v1/posts?exclude_postmeta_key=global and grab all posts that don't have the global post_meta attached to the post.

Is something like this possible?

1

1 Answer 1

0

Yes, it's surely possible, but not out-of-the-box.

I.e. There's no such REST query parameter in the WordPress core, but you can add it to your REST API request, e.g. via the URL query string, and then use the rest_<post type>_query hook which "Filters WP_Query arguments when querying posts via the REST API" and "Enables adding extra arguments or setting defaults for a post collection request".

And here's an example for the post post type:

add_filter( 'rest_post_query', 'my_rest_post_query', 10, 2 );
function my_rest_post_query( array $args, WP_REST_Request $request ) {
    if ( $meta_key = $request->get_param( 'exclude_postmeta_key' ) ) {
        $args['meta_key']     = $meta_key;
        $args['meta_compare'] = 'NOT EXISTS';
    }

    return $args;
}

So with that, example.com/wp-json/wp/v2/posts?exclude_postmeta_key=global would now give you the posts that do not have the meta named global.

If you need help with WordPress meta query, see the documentation. ( and/or post another question :) )

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.