Site icon Hip-Hop Website Design and Development

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.