1

So WordPress offers the default Rest API endpoint, which is: https://example.com/wp-json/wp/v2/posts which pulls in all the posts.

Is there a way to configure and modify the existing /wp/v2/posts endpoint to exclude posts that have a post_meta of global_post?

1 Answer 1

2

Caveat

From the REST API docs:

Changing or removing data from core REST API endpoint responses can break plugins or WordPress core behavior, and should be avoided wherever possible.

That said, there's a rest_post_query filter (well, rest_{$this->post_type}_query) that will let you modify the WP_Query that's grabbing your posts, so you should be able to add a meta_query to the query.

eg:

add_filter( 'rest_post_query', 'wpse405394_remove_global_posts', 10, 2 );
/**
 * Removes the "global_post" posts from the REST API.
 *
 * @param  array           $args    The WP_Query arguments.
 * @param  WP_REST_Request $request The REST request.
 * @return array                    The filtered $args.
 */
function wpse405394_remove_global_posts( $args, $request ) {
    if ( empty( $args['meta_query'] ) ) {
        $args['meta_query'] = array();
    }
    $args['meta_query'][] = array(
        'key'     => 'global_post',
        'value'   => true,
        'compare' => '!=', 
    ); 
    return $args;
}

This code is not tested, and may break things in your site. A lot of things use the REST API under the hood (eg: the block editor). Test thoroughly.

References

3
  • Thanks @Pat, I did not know it can be that impactful, would it be better to create a custom endpoint and then do the same that wp/v2/posts is doing, excluding the post_meta posts?
    – Sema
    May 3 at 16:36
  • How would this be possible to be built? Pull in all posts excluding post_meta 'global_post' posts, on the custom endpoint.
    – Sema
    May 3 at 16:36
  • I have this other question posted if you can take a peak at it: wordpress.stackexchange.com/questions/405385/…
    – Sema
    May 3 at 16:38

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.