Support » Plugin: WordPress Popular Posts » How To: Updating the views count via AJAX

  • Plugin Author Hector Cabrera

    (@hcabrera)



    This is a follow-up / update to “[Plugin: WordPress Popular Posts] using the jQuery load() method”.

    Some themes use AJAX to retrieve and display posts and pages. In these conditions WPP won’t be able to update the views count of these posts because the single.php template is not loaded by the theme.

    To work around that, you can send a POST request to WordPress via AJAX once your AJAX script has been executed to tell WPP to update the views count. For example:

    var ajax_url = '<?php echo admin_url('admin-ajax.php', is_ssl() ? 'https' : 'http'); ?>';
    
    jQuery.get(
        ajax_url,
        YOUR_PARAMS_HERE,
        function(response) {
    
            // YOUR
            // CODE
            // GOES
            // HERE
    
            // ... and then, let's update the views count of this post / page
            jQuery.post(
                ajax_url,
                {
                    action: 'update_views_ajax',
                    token: '<?php echo wp_create_nonce('wpp-token') ?>',
                    wpp_id: POST_ID_GOES_HERE
                },
                function(response){
                }
            );
    
        }
    );

    Of course, you’ll need to adapt this code to your needs. Pay attention to YOUR_PARAMS_HERE and POST_ID_GOES_HERE since you’ll need to change those as well.

    Have fun!

    https://wordpress.org/plugins/wordpress-popular-posts/

Viewing 12 replies - 1 through 12 (of 12 total)
  • Any pointers for how to make this work in combination with the “Ajaxify WordPress Site” plugin (https://wordpress.org/plugins/ajaxify-wordpress-site/) ?

    Any help would be much appreciated!
    Thanks

    I got this far, but it’s not updating the view count.

    $( document ).ajaxStop(function() {      
       jQuery.post(
                my_script_vars.ajaxurl,
                {
                    action: 'update_views_ajax',
                    token: my_script_vars.nonce,
                    wpp_id: my_script_vars.postID
                },
                function(response){
                }
            );
    });
    Plugin Author Hector Cabrera

    (@hcabrera)

    Hi there!

    I honestly have never used the Ajaxify WordPress Site plugin so I have no idea how it works.

    What does response returns?

    Hey, thanks so much for your reply!

    When I use response to e.g. console.log the nonce, it keeps logging the nonce token again and again – indefinitely. Not sure what that means…?
    Can I do another test to find out why it’s not working?

    Thanks

    Plugin Author Hector Cabrera

    (@hcabrera)

    Try this:

    var wpp_ajax_data = {
      action: 'update_views_ajax',
      token: my_script_vars.nonce,
      wpp_id: my_script_vars.postID
    };
    
    if ( window.console && window.console.log ) {
      window.console.log( wpp_ajax_data );
    }
    
    jQuery.post(
      my_script_vars.ajaxurl,
      wpp_ajax_data,
      function( response ){
        if ( window.console && window.console.log ) {
          console.log( response );
        }
      }
    );

    Also, my guess is that it executes again and again because the ajaxStop function is triggered every time an Ajax call has finished executing on your document (page). If you have several Ajax calls it’ll be triggered several times as well. If that’s true, then this script will update the views count of a given post N times (instead of just once).

    Yes, you’re right. now it keeps logging
    Object {action: "update_views_ajax", token: "51c632ac3d", wpp_id: "1237"}

    However the posts I browse still don’t appear in the Stats tab.

    Plugin Author Hector Cabrera

    (@hcabrera)

    Alright, I took a look at AWS’ ajaxify.js script just now. Try adding this right after this line and report back with the results.

    Now the console log only appears whenever I browse to a different page. However the token and wpp_id don’t change and the views are still not counted.
    Is it maybe because I defined those variables ‘my_script_vars.nonce’ and ‘my_script_vars.postID’ through a function in function.php?

    Plugin Author Hector Cabrera

    (@hcabrera)

    Not sure. Please post the code snippet from your functions.php file here so I can take a look at it.

    This is it:

       function load_my_script() {
            global $post;
            $deps = array('jquery');
            $version= '1.0'; 
            $in_footer = true;
            $nonce = wp_create_nonce( 'wpp-token' );
            wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/yt.js', $deps, $version, $in_footer);
            wp_localize_script('my-script', 'my_script_vars', array(
                    'postID' => $post->ID,
                    'ajaxurl'       => admin_url( 'admin-ajax.php' ),
                    'nonce'=> $nonce
                )
            );
        
    }
    add_action('wp_enqueue_scripts', 'load_my_script');
    Plugin Author Hector Cabrera

    (@hcabrera)

    Aha! The problem is that load_my_script() is only called once (when your site loads the first time) hence the post ID will never change when AWS loads another page via Ajax.

    You need a different workaround to ensure that the $.post script receives the right ID after AWS is done loading the page. One way could be by modifying its ajaxify.js script to have it retrieve the post/page ID from the body class (assuming your theme uses the body_class() function) and then use it with the $.post script.

    Yes, that was indeed the problem!
    I used this

    var id, matches = document.body.className.match(/(^|\s)postid-(\d+)(\s|$)/);
    if (matches) {
        // found the id
        postid = matches[2];
    }
    console.log('Post id:' +postid);

    just before:
    var wpp_ajax_data = ...
    to get the post id from the body class and now the views get logged 🙂

    Thank you so much for your help!

Viewing 12 replies - 1 through 12 (of 12 total)
  • The topic ‘How To: Updating the views count via AJAX’ is closed to new replies.