Domanda

For a custom 'Most popular posts' widget, I created a function that creates/updates a post meta to save the number of posts views and I included this function in the single.php template.

It works just fine till I installed WP Super Cache, the number of views stay unchanged.

How can I use this function with the WP Super Cache activated?

This is the function included in the single.php:

function save_views($postID){
  $metakey = 'postsViews';
  $views = get_post_meta($postID,$metakey,true);
  $count = (empty($views) ? 0 : $views);
  $count++;
  update_post_meta($postID,$metakey,$count);
}
remove_action('wp_head','adjacent_posts_rel_link_wp_head',10,0);
È stato utile?

Soluzione

When using WP Super Cache, the plugin generates static HTML files for your templates, which means that any PHP code you're running will only ever run when the cached page is generated or regenerated.

So if you need to trigger PHP code on every page load from behind a cache, you'll need to use AJAX.

So for your use case you'll need two functions added to your functions file. Firstly you'll need to add the Javascript that makes the AJAX request to the footer of all of your posts. This will do that:

function my_count_views_script() {
    if ( is_single() ) :
        ?>
        <script>
            jQuery.post({
                url:     '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                action:  'my_count_views',
                post_id: <?php the_ID(); ?>
            });
        </script>
        <?php
    endif;
}
add_action( 'wp_footer', 'my_count_views_script' );

This sends a request to the admin-ajax.php file with the post_id of the post being viewed and the action we want to perform with it.

To count this view, you need to tell admin-ajax.php what code to run when it received a request with the my_count_views action. You do this by hooking onto wp_ajax_my_count_views (to handle it for logged in users) and wp_ajax_nopriv_my_count_views for logged out users:

function my_count_views() {
    if ( isset( $_POST['post_id'] ) && $_POST['post_id'] ) {
        $post_id = intval( $_POST['post_id'] );
        $views = intval( get_post_meta( $post_id, 'postsViews', true ) ) ?: 0;
        $views += 1;

        update_post_meta( $post_id, 'postsViews', $views );
    }

    wp_die();
}
add_action( 'wp_ajax_my_count_views', 'my_count_views' );
add_action( 'wp_ajax_nopriv_my_count_views', 'my_count_views' );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top