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. Tony Bellardi says:

    GREAT !

  2. bent says:

    Hello,
    Thank you for the answer.
    I found some information how I can resolve the problem.

    In the articles they tell that we can put dynamic content –

    <!-- mfunc -->any PHP code<!-- /mfunc -->

    So w3-total-cache will not cashing this PHP Code.

    I tried it in single_news.php in this way, but it’s not working again.

    <!-- mfunc echo bac_PostViews(get_the_ID()); -->
    
    <!-- /mfunc -->

    Because you are the expert, can you give me the solution with mfunc? I believe that it will be useful for everybody.
    Thank you!

    Merry Christmas and Happy New Year!

  3. Steve says:

    While I understand – to a degree – your resistance to using plugins, this is a perfect example of something that SHOULD be in a plugin, not in a theme.

    What if the user changes themes or updates their theme?

    A plugin with this functionality would add so little overhead to a page load that you could almost count it as non-existent. You would keep all of your code in one place for easy maintenance, and you can utilize WordPress filters for output.

    There is no shame in using a plugin when the alternative is code scattered between 4 or 5 theme files, especially when the specific function of the code is not theme-related.

  4. Iftekhar says:

    Thanks for the post. Its working. One thing I want to know. Each time I am refreshing my page count is also increasing. Is it ok?

    Thanks again

  5. Jim Rush says:

    This is almost what I was looking for. I want it to display the views outside of the loop, in category.php – I suppose I just have to keep looking.

    Anyway, if I don’t find it, I’ll use this code inside the loop!

    Thanks,
    Jim

  6. sarwan says:

    Thanks man, its working like a charm!

  7. Ram Hari Regmi says:

    Thanks for the great tips. It worked perfectly for me.

    Can we use the same count to find the most viewed post on my website.

  8. Lord Akoroth says:

    Hey!,

    Thanks a lot for the tutorial. it is very useful.

    Keep up the good work!

    (ps: your drag the blouse to shopping bag method for comment verification is kickass!)

  9. Ali says:

    Thank you! Works great :)

  10. Daniel Yanes Arroyo says:

    Great article! I really appreciate it.

    It would be great if we could somehow populate the post meta data with previous statistics from WordPress stats or Analytics. Our blog it’s 5 years-old and if we show this statistics from now on, they won’t represent our real traffic. I’m thinking on using the function on a hidden mode for a year, and then release the stats. Maybe we could just add a note with “Views counted since X day”

    Anyways, thanks again! :)

  11. Tomas says:

    Many many thanks for your code :)

  12. shohel says:

    Hi, Thanks it working for me. Now its showing when i click on a single post. But i want to show the counter on every post (no need to click on the post to see how many times the post is visited). what can i do? please help me. i am using Graphene theme.
    Thank you

    • Hi shohel,

      In this case you put part2 of the code (CODE-2) in ‘index.php’ file and style it to what you like.
      If you need further help with your “Graphene theme”, then please donate first (minimum of $20) to this blog and I’ll do
      it for you.
      Thanks.
      Boutros.