Yes, pre_get_posts
runs for REST API requests. Your issue is likely that your request is not properly authenticated, so $user_ID
is not set. To allow the REST API to recognise the logged-in user you need to send the wp_rest
nonce with the request. You can create this with wp_create_nonce( 'wp_rest' )
and send it with the request as the X-WP-Nonce
header. This is documented in more detail in the developer handbook.
It’s not relevant to your original question, but the code in your question will apply to all queries. This includes posts, pages, menus etc. So if you won’t want that behaviour you need to add some sort of check so that your code only applies to certain queries. For example:
function only_users_todos( $query ) {
if ( $query->get( 'post_type' ) === 'todo' ) {
$query->set( 'author', get_current_user_id() );
}
}
add_action( 'pre_get_posts', 'only_users_todos' );
Also, pre_get_posts
is an action, not a filter, so you don’t need to return $query
.