Counter posts and pages viewed – WordPress

How to display the total access to posts and pages? We will modify the plugin “post-views” so it also works as an access counter (hits).

Problem

The “post-views” is a plugin that logs how many times your post/page was visited, with detailed analysis. But in truth, I didn't make this Post to say that, even by that, has several plugins in the genre that do something similar.

What I wanted was to display the total amount of hits on the Blog since I started counting, but I didn't find this functionality in “post-views”.

It turns out that, How do I use this plugin for some time now and I already have a populated database, that wasn't the case use another plugin because I wasn't that ready. So, I added the plugin a simple method to recover the total amount of access.

Solution

(1) Install the plugin “post-views” and activate it. To download it, visit the website of WordPress Plugins.

(2) After installation, open the “WP-content/plugins/post-views/post-views.php” and enter one of the following functions:

– Displays only normal access to the content of the post/page and disregards access done by robots (search mechanisms)

1
2
3
4
5
function get_total_post_views() {
  global $wpdb;
  $views =  intval($wpdb->get_var "($wpdb->prepare("select sum(' post_views_total ') From ' wp_post_views_realtime ' where ' view_type ' = ' normal ' and ' output_type ' = ' content '", APP_POST_TYPE)));
  return number_format($views,0,',','.');
}

– Displays normal access to the content of the post/page and also access done by robots (search mechanisms)

1
2
3
4
5
function get_total_post_views() {
  global $wpdb;
  $views =  intval($wpdb->get_var "($wpdb->prepare("select sum(' post_views_total ') From ' wp_post_views_realtime ' where (' view_type ' = ' normal ' or ' view_type ' = ' robot ') and ' output_type ' = ' content '", APP_POST_TYPE)));
  return number_format($views,0,',','.');
}

(3) Now it's just making the call at the location of the page you want to display, as for example in the file “footer.php” of your template:

1
  Total hits: <?PHP echo get_total_post_views() ?>

(4) Finally, If you want to display the total access to every Post specifically, place this code in your theme's single.php page your (WP-content/themes/):

1
2
3
if(function_exists(' get_post_views ')) { 
    echo ' Total hits: ' . get_post_total_views();
}

That's it, now the plugin “post-views” will act as an access counter (hits) for posts and pages viewed.

See the footer of this Blog to see how it looks!

Total hits: 12976

4 comments on “Counter posts and pages viewed – WordPress

Leave a reply

The your email address will not be published. Required fields are marked with *