How do you track your most viewed posts?

Hello all! I would like to display my most viewed posts on my React homepage. I have read a couple tutorials - like https://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/ - and while I can install a custom plugin just fine, I think the problem is that it doesn’t register a “view” on my post in React as a pageview. Has anyone encountered this issue before? Do you have any ideas on how to tackle this?

Hi @jeanette

Welcome to the community.

This is not going to be simple to do, but it could be done. As you’ll see from the article you refer to WordPress doesn’t do this by default and needs some custom code to register post views. You would need to do something similar in React, but you have the added complication of then sending the page view registration back to WordPress and then storing it in the meta with the post as demonstrated in the article. So it will involve both client side JS/React code and server side PHP code. In addition, as you’re sending data back to the server you will need to authenticate each Send to prevent malicious actors sending to the same endpoint. You should also take extra measures to ensure that you’re not creating any security issues as you’re writing data from client to server.

On the whole I think that this might be quite a challenging programming task. But certainly doable with enough perseverance.

Good luck. Do let us know how you get on with this.

Hi @jeanette

On second thoughts I think you could do this server side in WordPress. The solution might be largely similar to the one in the article that you cite, but hooked onto the rest_pre_echo_response hook, rather than wp_head as they do in that article. I think it could be worth experimenting with this approach.

In either case, you would also need to add the post meta to the post data returned by the WP REST API so that you have access to it from your Frontity app.

1 Like