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?
1 Answer
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.
-
-
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. May 16, 2022 at 23:27