How to Display Post Views in WordPress Without any Plugin

by • On Jan 10, 12 1:25am, Updated: Mar 12, 12 5:58am • 2566 Views

WordPress TricksIf you are visiting our site on regular basis, you must have noticed that we are displaying the total Views for every single post. Yes, we are still using a Plugin (WP-PostViews) to do that. But there are ways to do nearly the same thing without any Plugin.

Personally, I am not a huge fan of Plugins. I would rather go with the Snippet codes rather than using Plugins, even though Plugins are normally much easier to use.

Today, I will share a snippet code with you all and will explain you how to make it work. So let’s get started.

Step 1: Log in to your WordPress site and go to “Editor” from “Appearance” menu.

Step 2: Copy the following code and Paste it on your theme’s functions.php file.

function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View"; }
return $count.' Views'; }
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
$count++ ;
update_post_meta($postID, $count_key, $count); } }

Step 3: Copy the following code and Paste it on single.php file’s loop. This will help us to collect the data.

<?php setPostViews(get_the_ID()); ?>

Step 4: Now, copy and paste the following code wherever you want display the counts. It could be on your index.php or single.php file. However, it works on sidebar.php as well.

<?php echo getPostViews(get_the_ID()); ?>

Please understand that, this code will help you to display the total number of each Post Views only. I personally tried this code on some of my custom made theme and it worked. I hope this snippet code will be helpful for you as well.

Update: Check out “How to Display Post Views on WordPress Admin Posts Panel Without Any Plugin” which is an extension of this snippet code.

However, if you can’t make it work for some reason, feel free to ask question on our comment section. We will get back to you.

You can follow us on Twitter, add on your Google+ circle or Like our Facebook page to get the latest news, updates and reviews.