1

The title says it all: Is it possible to set a condition in pre_get_posts that only applies to queries that are targeted at the REST API?

So at https://example.com/wp-json/wp/v2/

1 Answer 1

2

Yes.

So long as the code you're running happens after parse_request - which pre_get_posts does. (See https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request)

Then you will have a nice constant to use: REST_REQUEST

Something like

if( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
    // ...do RESTy things
}

will do the trick.

See /wp-includes/rest-api.php

2
  • Thanks. Seems to work like a charm.
    – MastaBaba
    Mar 31, 2022 at 14:30
  • Actually, this doesn't seem to quite always work as expected: To avoid targeting all queries, you can use $query->is_main_query(), but this doesn't seem to work in combination with this if-then.
    – MastaBaba
    May 16, 2022 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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