Count Page Hits in WordPress

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie