If you’re building a WordPress site with AngularJS as a Single Page Application (SPA), and you want to record views for posts fetched through the JSON API, you’re in the right place. In this guide, we’ll walk through the process step by step, addressing the questions raised in the discussion.

1. Fetching a Post using JSON API

You mentioned using the endpoint /wp-json/wp/v2/posts/{id} to fetch a post in your AngularJS application. This is a common approach for retrieving post data. Now, let’s move on to the next steps to record post views.

2. Selecting the Right Hook for API Requests

In WordPress, hooks are essential for executing custom code at specific points in the application flow. The discussion mentions the posts_selection hook, but it seems it doesn’t fire for REST API requests.

Solution: Use the rest_pre_echo_response hook, which is triggered during REST API responses. This hook provides the response data, server instance, and request information.


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, like updating post meta
update_post_meta( $post_id, 'views', get_post_meta( $post_id, 'views', true ) + 1 );

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

3. Handling Conditional Logic

You might wonder why the posts_selection hook doesn’t work for REST API requests. The reason is that the execution flow is different. The rest_pre_echo_response hook allows you to modify the response data before it is sent to the client.

Additional Tips:

By following these steps, you can successfully record post views for your Angular SPA WordPress implementation. Remember to adapt the code to fit your specific requirements, and always test thoroughly to ensure proper functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *