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. Elisa says:

    Hi,
    Thank you for your code…
    I would like to know if it is possible to reset all the statistics of visits each month automatically. How can I do? I have seen other similar comments but I could not find the answers.
    Thank you for an answer.

  2. Drink says:

    So how can I display view count during reading post summary?