Rest API Hook When Post Is Requested

My original answer was all wrong, so it’s been removed in it’s entirety.

Neither the posts_selection nor wp hook are fired during the REST API request.

The hook you need is rest_pre_echo_response. This hook passes three parameters:

  1. The response data to send to the client
  2. The server instance.
  3. The request used to generate the response.

Since you need the post ID, you can do something like:

add_filter( 'rest_pre_echo_response', function( $response, $object, $request ) {
  //* Get the post ID
  $post_id = $response[ 'id' ];

  //* Make sure of the post_type
  if( 'post' !== $response[ 'post' ] ) return $response;

  //* Do something with the post ID

  //* Return the new response
  return $response;
}, 10, 3 );

Leave a Comment