How To: Updating views count via AJAX
-
WordPress Popular Posts sends a POST request via AJAX to the REST API to track page views. There’s a JavaScript object that I believe should be available globally called
WordPressPopularPosts
that you could use to save you some typing. Here’s how the plugin uses it:WordPressPopularPosts.post( wpp_params.api_url + '/wp-json/wordpress-popular-posts/v2/views/' + wpp_params.ID, "_wpnonce=" + wpp_params.token + "&sampling=" + wpp_params.sampling_active + "&sampling_rate=" + wpp_params.sampling_rate, function( response ) { wpp_params.debug&&window.console&&window.console.log&&window.console.log(JSON.parse(response)); } );
(see wpp.js for more details.)
As you can see, the
post()
method of the object expects three parameters:- The URL of the REST API endpoint WPP uses to track page views (eg.
https://www.example.com/wp-json/wordpress-popular-posts/v2/views/[POST_ID_HERE]
), where [POST_ID_HERE] is a valid post / page / custom post type ID. - The parameters
_wpnonce
, a valid WordPress Nonce called _wpnonce;sampling
, whether Data Sampling is enabled or not on your site (0 = disabled, 1 = enabled); andsampling_rate
, the Sampling Rate. - A JS callback function to be executed after updating the views count.
If you don’t want to use the
WordPressPopularPosts
object you can also just make a regular AJAX call using the same exact parameters (url, args, etc) and you should be good to go. - The URL of the REST API endpoint WPP uses to track page views (eg.
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.