How To Track & Display Post Views Count in WordPress Without a Plugin

Do you want to know how many times a post has been viewed on your Blog? In this tutorial, I will show you how to count post views and display it on your WordPress Blog and also in the dashboard without the need of a plugin. Probably you already have seen some Blogs displaying a View Counter for each post and you wonder how it is done.

You have the option to display Post Views on your Blog alone (Front-End only), in your Dashboard alone (Back-End only), or in both your Blog and Dashboard (Front-End and Back-End).

For this blog, I am displaying the total Views for every single post. The code counts views when you refresh or view the post, it does not discriminate between visitors. The code will start tracking and displaying post views from the time you add it to your WordPress theme.

What About a Plugin?

Yes, there are plugins that count Post Views but they all tend to do a lot more than you need. Also I encourage you to read my previous article about unnecessarily adding plugins to your theme. Personally, I am not a fan of plugins, I prefer to use a Snippet of code rather than using Plugins.

Final Result | Front-End

The pictures below show an example of the Post Views Counter displayed at the top of each post for this blog, and for each of the 4 themes I have available for my visitors.

Paper Wall theme: Post Views Count.

Clear Line theme: Post Views Count.

Emplode theme: Post Views Count.

Diary theme: Post Views Count.

Track Post View Count | functions.php

In your Blog (Front-End), you can display the Post View Counter by doing the following: Open the functions.php file located in your theme´s folder, and add (copy and paste) the following CODE-1. Save the file and upload it to the server.

CODE-1 :: Sets, Tracks and Displays the Count of Post Views

Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

<?php
/************************************CODE-1***************************************
* @Author: Boutros AbiChedid 
* @Date:   January 16, 2012
* @Websites: http://bacsoftwareconsulting.com/ ; http://blueoliveonline.com/
* @Description: Displays the Number of times Posts are Viewed on Your Blog.
* Function: Sets, Tracks and Displays the Count of Post Views (Post View Counter)
* Code is browser and JavaScript independent.
* @Tested on: WordPress version 3.2.1 
*********************************************************************************/
//Set the Post Custom Field in the WP dashboard as Name/Value pair 
function bac_PostViews($post_ID) {

	//Set the name of the Posts Custom Field.
	$count_key = 'post_views_count'; 
	
	//Returns values of the custom field with the specified key from the specified post.
	$count = get_post_meta($post_ID, $count_key, true);
	
	//If the the Post Custom Field value is empty. 
	if($count == ''){
		$count = 0; // set the counter to zero.
		
		//Delete all custom fields with the specified key from the specified post. 
		delete_post_meta($post_ID, $count_key);
		
		//Add a custom (meta) field (Name/value)to the specified post.
		add_post_meta($post_ID, $count_key, '0');
		return $count . ' View';
	
	//If the the Post Custom Field value is NOT empty.
	}else{
		$count++; //increment the counter by 1.
		//Update the value of an existing meta key (custom field) for the specified post.
		update_post_meta($post_ID, $count_key, $count);
		
		//If statement, is just to have the singular form 'View' for the value '1'
		if($count == '1'){
		return $count . ' View';
		}
		//In all other cases return (count) Views
		else {
		return $count . ' Views';
		}
	}
}
?>

CODE-1 Notes:

The code accurately counts post views (based on refresh rates of the post) even if you are using a theme switcher as in this blog. You still have to add the code in every theme. Changing between themes does NOT reset Post Views Counter.

The post meta data is the “administrative” information you provide to viewers about each post.

Some themes have more variations of the functions.php file, so look at their documentation and see where best to add the code.

CODE-1 is tested to work on all major browsers and does not rely on JavaScript.

CODE-1 References:

Display the Post View Counter on Your Blog (Front-End) | single.php

After adding CODE-1. Now to display the Post View Counter, you need to add the Template Tag (CODE-2) to your theme´s single.php file. Add it where you want the Post View Counter to appear. Remember that CODE-2 must be added within the loop, otherwise it will not work.

What is “The Loop”? The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. When WordPress documentation states “This tag must be within The Loop”, such as for specific Template Tag, the tag will be repeated for each post.

CODE-2 :: Post Views Template Tag

<?php if(function_exists('bac_PostViews')) { 
	echo bac_PostViews(get_the_ID()); 
}?>

Why do you Wrap the template tag, bac_PostViews(), inside an If Statement?

It is important to make it conditional. Otherwise, if bac_PostViews() does not exist or there is a problem loading it you will get an Error message: “Fatal error: Call to undefined function bac_PostViews() in…”. However, by wrapping it in a conditional statement the Website loads without any errors.

CODE-2 requires CODE-1.

Real Example | Where to Add CODE-2 in Your Theme

This is where I added CODE-2 for the “Emplode Theme” of this Blog (in single.php file).

<?php get_header(); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div class="post" id="post-<?php the_ID(); ?>">
    
<div class="post_title"><h2><?php the_title(); ?></h2></div>
        
<div class="post_date">Posted on <?php the_time('F jS, Y') ?> by <?php the_author(); ?><?php edit_post_link('Edit post', ' | ', ''); ?> |  <?php if(function_exists('bac_PostViews')) { echo bac_PostViews(get_the_ID()); }?>  <!-- Display post view count. -->         
</div>	

<div class="post_body">
				
<!-- part of the single.php code removed for brevity. --> 

</div> 	
</div>

<?php comments_template(); ?>

<?php endwhile; else: ?>

<!-- part of the single.php code removed for brevity. --> 

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Styling the Post Views Counter | style.css

To style the Post Views Counter with CSS, use the same code as your Post meta styles. You don´t have to do anything extra here unless you want to. Style it with what´s available for your theme.

Display Post Views Column In WordPress Dashboard | functions.php

Open the functions.php file located in your theme´s folder, and add (copy and paste) the following CODE-3. Save the file and upload it to the server.

Then Login to your WordPress dashboard. In your Administration Screens go to the “Posts” tab, and you will notice a new Views column that tracks the number of views of each post as shown below:

Final Result | Back-End (Dashboard)

The picture below shows the Views Column added to the “Posts” tab in the WordPress dashboard for this blog.

Views Column for the Posts tab as it shows in the WordPress dashboard.

CODE-3 :: Creates a Post Views Column in the Dashboard

Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

<?php
/*********************************CODE-3********************************************
* @Author: Boutros AbiChedid 
* @Date:   January 16, 2012
* @Websites: http://bacsoftwareconsulting.com/ ; http://blueoliveonline.com/
* @Description: Adds a Non-Sortable 'Views' Columnn to the Post Tab in WP dashboard.
* This code requires CODE-1(and CODE-2) as a prerequesite.
* Code is browser and JavaScript independent.
* @Tested on: WordPress version 3.2.1
***********************************************************************************/ 

//Gets the  number of Post Views to be used later.
function get_PostViews($post_ID){
    $count_key = 'post_views_count';
    //Returns values of the custom field with the specified key from the specified post.
	$count = get_post_meta($post_ID, $count_key, true);

	return $count;
}

//Function that Adds a 'Views' Column to your Posts tab in WordPress Dashboard.
function post_column_views($newcolumn){
	//Retrieves the translated string, if translation exists, and assign it to the 'default' array.
    $newcolumn['post_views'] = __('Views');
    return $newcolumn;
}

//Function that Populates the 'Views' Column with the number of views count.
function post_custom_column_views($column_name, $id){
	
	if($column_name === 'post_views'){
		// Display the Post View Count of the current post.
		// get_the_ID() - Returns the numeric ID of the current post.
        echo get_PostViews(get_the_ID());
    }
}
//Hooks a function to a specific filter action.
//applied to the list of columns to print on the manage posts screen.
add_filter('manage_posts_columns', 'post_column_views');

//Hooks a function to a specific action. 
//allows you to add custom columns to the list post/custom post type pages.
//'10' default: specify the function's priority.
//and '2' is the number of the functions' arguments.
add_action('manage_posts_custom_column', 'post_custom_column_views',10,2);
?>

CODE-3 Notes:

If you added CODE-3 to your functions.php file, and you still don´t see the Views Column in your Dashboard, then make sure that your screen options is set to display the new column as shown in the image below:

WordPress dashboard: Screen options for Posts.

CODE-3 requires CODE-1 and CODE-2. You can´t use CODE-3 on its own.

You could Manually set the value of the Custom Field ´post_views_count´ to numbers or letters if you want and it updates the count accordingly.

IF YOU don´t want to show the Post Views Column in your admin area, remove CODE-3.

If you want to display Post View Count in your WordPress dashboard but NOT on your Blog, then you need to modify the above CODE-2 (just remove the echo language construct from line 2 of CODE-2, as follows:

CODE-2a :: Post Views Template Tag (MODIFIED)

<?php if(function_exists('bac_PostViews')) { 
	bac_PostViews(get_the_ID()); 
}?>

CODE-3 adds a Non-Sortable Custom “Views” Column for Posts in the Dashboard. If you want to be able to sort that custom column, then check my next tutorial: How To Make the “Views” Column Sortable.

CODE-3 References:

General Warning

When you add several PHP code blocks in your theme´s funtions.php file, make sure that you do NOT leave any white space (spaces, newline) before the opening PHP tag (<?php) or after the closing PHP tag (?>). The correct way is as follows:

<?php 
//Some Code here beetween the opening PHP tag (above) 
//and the closing PHP tag (below)...
?>
<?php 
//Some other Code here ...
?>

In the above code, if you leave any white space or a newline between lines 4 and 5, you will get the following error: “Warning: Cannot modify header information - headers already sent by…

One Disadvantage of the Code (CODE-1 & CODE-3)

The “Post View Counter” on the Front-End and Back-End does not work with a caching plugin. For instance, if you have W3 Total Cache or Quick Cache installed, the Post View Count will not be updated. With all that said, if your WordPress Website is lightweight and your images are compressed and optimized for the Web, then by disabling the caching plugin, you might not notice a significant increase in page load time. You could also flush the buffer as I discussed in Tip8 in my previous tutorial (as well you could implement other significant tips): 14 Tips for Maximum WordPress Performance & Speed.

Why the code does not work? Because the code counts every view as long as you refresh or view the post. With a caching plugin, the post is not being refreshed/loaded from the server but, in most cases, served locally from your computer. That´s why the Post View Counter will not update.

For this blog, I am not using any caching plugin since I have multiple WordPress themes for my visitors to choose from.

To Recap! In case You are Confused

I want to display Post Views on my Blog AND on my WordPress Dashboard: In this case, use CODE-1, CODE-2 AND CODE-3.

I want to display Post Views on my Blog ONLY (but Not on my WordPress Dashboard): In this case, use CODE-1 AND CODE-2.

I want to display Post Views on My WordPress Dashboard ONLY (but Not on my Blog): In this case, use CODE-1, CODE-2a AND CODE-3.

How This Code Could be Improved

The Post View Counter code above, specifically CODE-1, counts posts views based on visits or refresh rates. The post view counter increments for every time the single post reloads/refreshes. The code could improve as follows:

  1. Post Views Count does not increment for Logged-in users, by using the is_user_logged_in() function. See CODE-1 MODIFIED that takes into consideration Logged-In Users.
  2. Post Views Count increments only once per visitor per post by using PHP Sessions.

Can This be Done With Custom Post Types?

Apparently yes. Please read this comment thread.

Your Turn to Talk

You now have the choice to show the Post Views Count in your WordPress blog and in your WordPress Dashboard, and without a plugin. In the blog, the code displays how many times a post had been viewed. And in the dashboard the code adds a new column that tracks the number of views for your Posts.

How easy did you find this tutorial to implement? Do you have something to add or anything else to say? If so, please share your opinion in the comments section. Your opinion matters, unless it is a Spam.

References

If you found this post useful, please consider: linking back to it, subscribing by email to future posts, or subscribing to the RSS feed to have new articles delivered to your feed reader, or feel free to donate. Thanks!

About the Author |
Boutros is a professional Drupal & WordPress developer, Web developer, Web designer, Software Engineer and Blogger. He strives for pixel perfect design, clean robust code, and user-friendly interface. If you have a project in mind and like his work, feel free to contact him. Connect with Boutros on Twitter, and LinkedIn.
Visit Boutros AbiChedid Website.

63 Responses to “How To Track & Display Post Views Count in WordPress Without a Plugin”

  1. Thank You So Much for this awesome hack.

  2. Ali says:

    Hi,
    Really interesting post. But I still have an issue.
    when I add “meta_key=post_views_count&orderby=meta_value_num&” to the query_posts it doesn’t return anything and when I remove it I have posts that display.
    I added the functions in functions.php of my theme.

  3. Tag says:

    Hi, I’m trying to add code 1 to my functions.php, but every time I do so, my website crashes. It doesn’t give me an error message, it just doesn’t load. I thought it was some conflict with my plugins, but it also didn’t work. I thought it could be code 2, but even if I don’t have code 2, it crashes. Thoughts?

    • What theme are you using (a link?). I’ll download your theme and test it. I am not sure why it is crashing.
      Thanks.

      • Kate says:

        The same thing happened to me and now I can’t log in. I even tried to backtrack and delete the added code, but it didn’t take.

    • I tried Code 1 on both Twenty-Eleven and Twenty-Ten themes. Both times I got a parsing error indicating an unknown ‘<' at the next line (612 in Twenty-Eleven). Clearing your programming did not repair the problem and I had to upload a new functions.php file via FTP to get everything to work again. Same thing happened with Twenty-Ten.

      It clearly breaks the .php file somehow, but I was unable to find the phantom code. Could it be that your programming should go at the beginning of the functions.php file or somewhere in the midle of the file? I simply posted it at the end as I normally do and this time it would not work.

      I really need this for a special project and none of the other plugins will do exactly what I need. Can you help?

      • Sure I can help you out. But please donate first (minimum of $25 (USD)). The donation button is at the top of the Blog.
        Thanks.
        Boutros.

        • smallwebmaster says:

          I will be happy to donate $25 USD for your professional assistance on this issue. However, before I do, I want to give you a little more information:

          I do not intend on using Twenty-Ten or Twenty-Eleven for this project. Those were just my test templates. The final version of this new website will be using a theme from either Studio Press or Elegant Themes. I’m not sure which at this point. The data for the final site will be from a Joomla site that has a long and important history, but Joomla has become unwieldy and WordPress will allow easier management so it can continue to grow. Some of the articles on the site have over 10,000 views and the site uses a post counter like the one you suggest. After the transfer, we want to capture all of those views for each post, enter them into the database, and then pick up the numbers from there on the new site.

          My point is that your programming allows us to do exactly what I need to do, but fixing the functions.php problem for just Twenty-Ten or Twenty-Eleven is not enough. This needs to work on all themes, like you show on your own very nicely designed site.

          Let me know if this is possible and your $25 is on the way.

          John

        • Hi John,

          The code will work on many themes. To guarantee that the code works on all themes, that would be impossible. I already use it on at least 10 themes myself and it works great like you see it on this blog.
          The code will start recording the views from the time you add it to your ‘functions.php’ file.
          For past views, you need to add those manually. Then the code will start incrementing from your initial data input. If you have many posts then you need to automate the process.
          The donation is to get the code to work on twentyten, or twentyeleven or any other theme of your choosing.
          Later on, if you still have issues when you go live, then you can use the ‘Hire Me’ page to contact me directly.
          Thanks.

  4. Afro-Spanish says:

    Thank you so much for this blog post. I have been looking for a way to show post views but have been unsuccessful with it. Have tried some plugins that messed things up without doing what i wanted it to. Thanks again for sharing this :)

  5. Armand says:

    Can you do this with a Custom Post Type? Does the code need to be modified to accomodate this? Thanks.

    • Hi Armand,
      No the code does not work for custom Post Types. Yes you have to modify the code for CPTs, If you know how, or find a solution please share it here for everybody to learn.
      See the next tutorial, which is the next logical step to this tutorial.
      Good Luck.

      • Armand says:

        Boutros,

        I found the fix for custom post types. It was pretty easy. Just change two lines and you’re all set.

        Change CUSTOMPOSTTYPENAME below to the name of your custom post type and it works perfectly.

        add_filter('manage_CUSTOMPOSTTYPENAME_posts_columns', 'post_column_views');
        add_action('manage_CUSTOMPOSTTYPENAME_posts_custom_column', 'post_custom_column_views',10,2);
        
        • Thanks Armand, that’s great. I’ll test it with some fake post types on my Blog. I want to see, when adding your 2 lines of code to the end of CODE-3, if it works with a combination of posts and CPTs.
          And if this works I’ll update this tutorial accordingly.

  6. neiker says:

    Thank you!

  7. yash says:

    how to sort most popular posts for today, this week or this month

    this is my code

  8. I am using 3.3.1 too and it’s not working for me. I get the total number of views on every single article, not the individual number. Good work anyway!

    • I am using WordPress 3.3.1 also, and it works. This is more of an issue with the theme that you are using. Also the code would not work for custom post types.
      Just for curiosity, what WordPress theme are you using?
      Thanks Chris for your feedback.
      Boutros.

  9. Blog-ID says:

    its not working for me… im using wordpress 3.3.1 and Mantra theme…

    • I am sure if you read the tutorial, and implement it correctly, it will work for you.
      But your goal here, is just to add comments for PR and Backlinks and nothing else.
      That’s why I removed your blog link.

  10. Amy says:

    Interesting code thank you! I was wondering if you wanted to then display these posts in the loop and sort them by their view count. How would you go about doing this using this function?

  11. Faruk says:

    THX man, this is really a great article, you saved my life. And also the article (how-to-display-most-viewed-posts-in-wordpress-without-a-plugin) Explanations, code, everything…thumbs up!
    Better than using a plugin definitely.

    Best regards,

    Faruk

  12. J says:

    Hi! It’s me again, I am following many of your tutorials because they’re great and I also think it is better to add functions with code rather than plugins. I have followed all the steps, it works perfectly. Question1: I would like to use the is_user_logged_in() so that it doesn’t count logged users, how do i use it?

    Question2: If I used a stats plugin such as google analytics or jetpack, is there a way to retrieve the data of the visits those plugins have collected?

    Thanks again, I will credit all your help on my blog when it’s ready!

    • Hi J.
      For your Question2:
      Not sure how to do it with code. But What you can do, if you have the statistics for each post, is to fill out the ‘post_views_count’ Custom field value manually and the click ‘Update’ button
      Meaning: Go to your dashboard -> All Posts, then edit each post and scroll down for the Custom Fields. There you see the ‘post_views_count’ name and value. Edit the ‘value’ to whatever the statistics is giving you for every post and hit update.
      I know if you have too many posts that would be time consuming. But that’s one solution.

      For your Question1:
      Here is the Modified Code that takes into Consideration if the User is Logged-In: If the User is Logged-In don’t increment post Views counter.
      (Remember for WP to know if the User is Logged-in is when the dashboard (Back-end) and the Blog (Front-End) are both displayed On the SAME browser.
      If the dashboard is running on one browser (e.g Mozilla) and the Blog is displayed on Another browser (e.g IE), then the post View counter will increment).

      <?php
      /************************************CODE-1 (MODIFIED)***************************
      * @Author: Boutros AbiChedid 
      * @Date:   February 6, 2012
      * @Websites: bacsoftwareconsulting.com/ ; blueoliveonline.com/
      * @Description: Displays the Number of times Posts are Viewed on Your Blog.
      * Post Views are NOT counted if the User is Logged-in.
      * Function: Sets, Tracks and Displays the Count of Post Views (Post View Counter)
      * Post View Counter is NOT incremented for Logged-In users.
      * @Tested on: WordPress version 3.2.1 
      *********************************************************************************/
      //Set the Post Custom Field in the WP dashboard as Name/Value pair 
      function bac_PostViews($post_ID) {
      
      	//Set the name of the Post's Custom Field.
      	$count_key = 'post_views_count'; 
      	
      	//Returns values of the custom field with the specified key from the specified post.
      	$count = get_post_meta($post_ID, $count_key, true);
      	
      	//If the User is NOT Logged In:
      	if(!is_user_logged_in() ){
      		//If the the Post Custom Field value is empty. 
      		if($count == ''){
      			$count = 0; // set the counter to zero.
      			
      			//Delete all custom fields with the specified key from the specified post. 
      			delete_post_meta($post_ID, $count_key);
      			
      			//Add a custom (meta) field (Name/value)to the specified post.
      			add_post_meta($post_ID, $count_key, '0');
      			return $count . ' View';
      		
      		//If the the Post Custom Field value is NOT empty.
      		}else{
      			$count++; //increment the counter by 1.
      			//Update the value of an existing meta key (custom field) for the specified post.
      			update_post_meta($post_ID, $count_key, $count);
      			
      			//If statement, is just to have the singular form 'View' for the value '1'
      			if($count == '1'){
      			return $count . ' View';
      			}
      			//In all other cases return (count) Views
      			else {
      			return $count . ' Views';
      			}
      		}
      	//If the User is Logged In, just return the View count. 
      	//At a New Post, the $Count will be undefined until you log Out.
      	}else {
      		return $count . ' Views';
      	}
      }
      ?>
      

      Hope this helps.
      Boutros.