Rest API Hook When Post Is Requested

I am aware that I can use the endpoint /wp-json/wp/v2/posts/{id} to fetch a post.

I am building an implementation of WordPress that relies completely on the JSON API and its endpoints. It is an Angular SPA implementation, which means my hooks need to fire when a request is made via the API.

As such, if I want to record views for a post, I wanted to use 'posts_selection'. My first question is will this fire if the selection is made via /wp-json/wp/v2/posts/{id}

My second question is is there another hook or something that will also fire during API query for a post but which will pass the {id} of the post to my function?

Because when I do this:

function check_assembled_query( $query ) {
    var_dump( $query );
}

 add_action( 'posts_selection', 'check_assembled_query' );

$query doesn’t have the information I want. I would like the following workflow:

  1. Request a post using /wp-json/wp/v2/posts/{id} from AngularJS.
  2. Have the backend recognize this request and iterate a meta field of the post’s views using update_post_meta() which requires a post id.
  3. Return the post requested to my JavaScript function with all the post’s information, including aforementioned meta-info view-count.

EDIT: I take it post_selection doesn’t fire for REST API because when I do this:

function check_assembled_query( $query ) {
    var_dump( $query );
    die();
}

 add_action( 'posts_selection', 'check_assembled_query' );

I only get the dump on regular requests rather than requests to the JSON API.

1 Answer
1

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