Count Page Hits in WordPress
by c.bavota | Posted in Tutorials | 7 comments
Jul
21
2011
This is just a little snippet of code I wrote to count the number of hits on a specific page. I only wanted it to work on single post pages so I included the is_single() conditional tag.
function count_page_hits() {
if(is_single()) {
global $post;
$count = get_post_meta($post->ID, 'count_page_hits', true);
$newcount = $count + 1;
update_post_meta($post->ID, 'count_page_hits', $newcount);
}
}
add_action('wp_head', 'count_page_hits');
All the code does it increase the count whenever the single post page is accessed. Now you will have a custom field with the number of times the page is hit. With this data, you can start to create a list of popular posts or even a graph to show you in your dashboard which posts have received the most views on your site.
Tutorials on how to do those things will come out shortly.



Nice and simple. Bookmarked for future reference.
Please don’t add a DB write on every page view. For larger blogs that will bring them down instantly. Use Google Analitics to pull that information and cache it locally.
However if you have a small traffic site that what you propose will work just fine!
Great, I´m looking forward to the tuturial “How to implement the
list of the most popular posts”.
I don’t now if this is OK tu put a Database read/whrite on every page. For small Blogs it can works but for big blogs with hight volume of visitors it can be a problem.
So what classes as a small blog that it would safe to use this on without slowing it down? How many pages or how much traffic?
I am used to seeing counters for the hits on a website, but for counting the hits on a post is certainly something new. This way I can track which of my posts are most popular and then recommend it to my audiences. They should really include this in other web hosting servers other than wordpress.
But, How to call the Function and display the Counter? Any page/post counter (instead of single page) would be really awesome. I am using a Plugin for that & it work’s fine.. but I just don’t like the Plugin concept. Adding snippet codes to my fucntions.php file could make life lot easier.. Thanks.