• Plugin Author Hector Cabrera

    (@hcabrera)


    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:

    1. 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.
    2. The parameters _wpnonce, a valid WordPress Nonce called _wpnonce; sampling, whether Data Sampling is enabled or not on your site (0 = disabled, 1 = enabled); and sampling_rate, the Sampling Rate.
    3. 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.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Hector Cabrera

    (@hcabrera)

    … a million years later, I just realized that there’s a problem with the JS code above.

    It should be:

    WordPressPopularPosts.post(
        wpp_params.api_url + '/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));
        }
    );

    (-?-“)

    Plugin Author Hector Cabrera

    (@hcabrera)

    Since the JS code changed a little bit after the 7.0.0 release (it’s not something that should happen often so don’t worry about it) please use this instead:

    WordPressPopularPosts.post(
    wpp_params.apiUrl + '/v2/views/' + wpp_params.ID,
    "_wpnonce=" + wpp_params.token + "&sampling=" + wpp_params.sampling + "&sampling_rate=" + wpp_params.samplingRate,
    function( response ) {
    wpp_params.debug&&window.console&&window.console.log&&window.console.log(JSON.parse(response));
    }
    );
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.