Trigger Post Views in a Headless WordPress Environment using WPGraphQL

[ad_1]

Hi @tmcmn,

Thanks for the great plugin!

Don’t mention it, glad you like it!

Is there a way to trigger a post view on a headless WordPress site?

Yes there is. You can send an AJAX request from within your application to a specific WordPress REST API endpoint with some parameters to register a page view. See Using WordPress Popular Posts with an AJAX based site for more details.

Thread Starter
tmcmn

(@tmcmn)

Oh great, thanks for the quick reply! I looked at the support topic you linked to.

Running the following Javascript code in SvelteKit’s onMount function triggers a page view for me 😊:

await fetch(https://www.example.com/info/wp-json/wordpress-popular-posts/v1/popular-posts?wpp_id=${$page.params.id},{ method: "POST" });

Are the parameters _wpnonce, sampling, and sampling_rate optional then? I wouldn’t know how to generate a WordPress Nonce from a headless site in Javascript. But it seems to be working without those parameters anyways.

Thanks!

  • This reply was modified 1 hour, 14 minutes ago by tmcmn.

As far as I know _wpnonce is required, WordPress usually rejects any POST request to the API that don’t include that – but if it works for you then maybe SvelteKit is already passing that as part of the request? I’m not familiar with it so that’s my guess. Try testing your app in Incognito mode / a different browser and see if it still works.

Thread Starter
tmcmn

(@tmcmn)

I thought _wpnonce would be required too, but it seems to be updating the view count even in a different browser and in incognito mode without that parameter. SveliteKit doesn’t add anything to the request. Maybe it’s an issue with one of my plugins or WordPress settings 🤷

  • This reply was modified 36 minutes ago by tmcmn.

All good then. Do keep an eye on it and if something ever breaks then you know that that would be one of the first things you’d need to check on 😛

If you have any comments and/or questions you can always find me here 🙂

Have a nice day!

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer