Are you looking for a way to track post views without a plugin using post meta? While there’s probably a plugin for this, we have created a quick code snippet that you can use to track post views without a plugin using post meta in WordPress.
Instructions:
Add this code to your theme’s functions.php file or in a site-specific plugin:
function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ 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); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } // Remove issues with prefetching adding extra views remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
Optionally add this code as well to a column in the WordPress admin that displays the post views:
// Add to a column in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); function posts_column_views($defaults){ $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views'){ echo getPostViews(get_the_ID()); } }
This part of the tracking views code will set the post views. Just place this code below within the single.php file inside the WordPress Loop.
<?php setPostViews(get_the_ID()); ?>
Note about fragment caching: If you are using a caching plugin like W3 Total Cache, the method above to set views will not work as the setPostViews()
function would never run. However, W3 Total Cache has a feature called fragment caching. Instead of the above, use the following so the setPostViews()
will run just fine and will track all your post views even when you have caching enabled.
<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->
The code below is optional. Use this code if you would like to display the number of views within your posts. Place this code within the Loop.
<?php echo getPostViews(get_the_ID()); ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress testimonial plugins and how to Set Up Author Tracking in WordPress with Google Analytics.
Any idea of how to use this with a Custom Post Type?
awesome stuff exactly what I was looking for?
cool glad to hear you like the snippet enjoy.
Likewise can we count the number of images uploaded on the wordpress site, I am sure we can.. any clue?
Sorry for the delay!
http://wpsnipp.com/index.php/functions-php/count-total-number-of-jpg-gif-png-images-in-media-library/
Example of Bob is possible?
Most viewed posts
Post title3 100 views
Post title1 50views
Post title2 10 views
what is the impact of using this function over the WordPress database.. will I be able to clear of the logs (views) at set schedules.. ??
This is not a plugin with a lot of features simply this will increment the count in the post meta by one each time the post is viewed.
how to remove the “Views” word ?                 Â
Hi Joj,
You will see on line 09Â Â Â Â return $count.’ Views’;
replace that line with the bellow and that is it.
return $count;
Thanks for the snippet. I slightly modified setPostViews() to discount post views from Editors or above:
function setPostViews($postID) {
if (!current_user_can('level_7') ) :
   $count_key = 'post_views_count';
   $count = get_post_meta($postID, $count_key, true);
   if($count==''){
       $count = 0;
       delete_post_meta($postID, $count_key);
       add_post_meta($postID, $count_key, '0');
   }else{
       $count++;
       update_post_meta($postID, $count_key, $count);
   }
endif;
}
Thanks drew very cool.
Not working for me on localhost. Not sure why but every view, regardless if it’s an Editor level or above, gets counted.
On another note, how would you disable counting the view by the post’s author?
Oops. Wasn’t logged in as admin during testing. (facepalm)
Glad to hear you got things working.
Hey Kevin!
Tried this code out on a fresh WP 3.2 install and it works nicely. I however noticed that all though it should only increate the count by 1 mine does it by 4. Any suggestions what could be wrong?Â
Got the functions set up in the right place and the only change I did to it was to exclude counts from logged in visitors. Even without this change the code gives 4 views instead of 1.
Huh should only count by one, since its just count++ did you have any other people visit your site while it was running or multiple tabs open ?
Its on my localhost. Its really odd but might be just some browser thing. Thanks for a nice little snippet though!
Kevin,
First off, Â love the simplicity of this solution! I have the code working properly on my local server but noticed that when I reload my homepage (which contains my 5 most recent entries) Â each reload of my homepage ads a view to the count for each of the 5 posts. Â Is there any way to avoid that and only count the actual article page views? Thanks
Hi Rgsanchezz glad to hear you like the snippet. In regards to your question make sure you place setPostViews(get_the_ID()); within the single.php template or inside if(is_singular()) should also work if you don’t use a single.php template that should resolve the problem.
Did you use this snippet in a separate loop? If so, you should place the setPostViews(get_the_ID()); outside the “most viewed” loop so that it counts the +1 only for the currently displayed post and not everyone in the list. For Instance:
WRONG:
     Â
     Â
      ( )      CORRECT:                        ( )     Â
Sorry, I copy-pasted the code into the reply box. Shortlinkoed via codepad, check it there : )
http://codepad.org/QOUWc3XB
Its Just a fake nothing else, dude If you are checking in firefox it will show but if you checked your url in chrome and IE its not displaying there. When you check in firefox it will show only your views nothing else…and if you think its my problem, just tell me.
Hi Sunnysuffy well the snippet is not fake, however if you have caching software running on your copy of wordpress it would have problems working. Supercache, etc.
[…] good example of the kind of tips you’ll find on wpsnipp.com is “Track post views without a plugin using post meta.” Â Kevin begins by describing what the snippet will accomplish, and then giving you a […]
hey, its cool..
thanks a lot.
Cool glad you like the snippet.Â
amazing, thank you!
no problem @4f9649a2dc0c5d186623a62544564bfe:disqus glad you like the snippet!
Needless to say, this is an awesome snippet. But if there is a solution to make it work with caching plugins, for instance with W3TC, it would be even better.
Anyway, good work!
I have not looked into this, ill take a closer look at some of the plugins and see what I can do. Glad you like the snippet though.Â
Hey Kevin, I’ve been browsing through forums to hit a solution. Apparently many people having problems with excluding functions from being cached. Unfortunately, there seems to be no cure any cure so far. I’m sure there is. Let’s hope one of us comes up with something soon 🙂
hello, As i know W3TC has a “Ignored query stems” to filter out some functions from cache.
hi nice information, is it possible to use echo getPostViews(get_the_ID()); in admin panel posts section if i want to use post views only for personal/admin purposes
Yes you can I posted a snippet not long after just for that reason.
http://wpsnipp.com/index.php/functions-php/display-post-views-within-admin-post-columns/
This is awesome, it works brilliantly. I will use it on a new wallpapers site I’m working on. Noted down your site on the functions for future reference.
I wonder if something can be done to only record only 1 view per session for every user. That would be cool to prevent “fake” views when refreshing the page. If anybody can do that (if it’s even possible) that would be awesome.
Thanks @6c9628c836d0d3ed67e8ef3b43a993dd:disqus Glad to hear you like the snippet! I’m sure something like that could be done, however I would use this as a method to track popularity of a post rather then for detailed stats.
I’m having an issue with this, if i view the second newest post the newest post get’s 1 view added, any ideas why?
The only reason I can think of is that you don’t have the setPostViews(get_the_ID()); function within the single.php? can you confirm this is the case…
Yeah it’s in the single.php in the loop
I am having the same problem after setting up a most popular posts list in the sidebar, using the “most Popular posts using views post meta” article. setPostViews(get_the_ID());  is in the single.php. setPostViews(get_the_ID());  is in the single.php.Â
I’m also having an issue here. Mine is in single.php, I followed the instructions. However I notice that if I visit a post (with a post ID let’s say 20), another post (with post ID let’s say 22) also gets +1 on views count. The weird thing is, when I echo the post ID received by the function setPostViews, only the post ID 20 is displaying on my screen.
Well it should work without any issues, however if you edit the posts you can see the custom field added with the current post views. I would reload the one page and see if the custom field updates on both posts. What version of wordpress are you currently running?
I was having the same issue. It took me forever to figure it out. The problem is caused by WordPress loading relational links for the previous and next posts in the head. Firefox, by default, prefetches REL links with the value of Next so both posts are being “viewed”
The solution I found was to remove the action that adds this functionality to the wp_head function:Â remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);Â
 Chris, thanks for the comment I updated the post to let others know about this fix for the issue. I also added a link to your site. Thanks again,
Hi Wprebel, You may have a plugin or something else that caused a problem with the snippet. The snippet is fairly simple and just updates the post meta when a user loads the post, not much to go wrong. Without looking at your theme in detail I would just be guessing,
  @e4fcff6cc58dc5e1b2ab556d9cdb2cb2:disqus you need to use the getPostViews() function when you want to display post views and setPostViews() on the single.php.
[…] Track post views without a plugin using post meta […]
[…] Via : lien […]
This technique won’t work with cache plugin. I would like using WP-PostViews plugin as it provides a better compatibility with cache plugin.
This is true, it does not play nice with cache plugins. However as a quick snippet to track views it works quite well.
I would rename the post_views_count meta key to _post_views_count to make it hidden to avoid users editing the post views from custom fields.
Ahh good call Daniel, you could do that.
[…] you would like to display the number of views: <?php echo getPostViews(get_the_ID()); ?> Source →Track Post View Amount by Using Post MetaThis snippet will create a list of your most popular posts […]
Is there a way to make an overview of the most viewed posts?
Just like the populair in your sidebar, but with usage of the post view instead of the comments ?
Hi Alec,
I just finished a post for that yesterday and will be posting it in about an hour.
First time i visit your site, and already my hero! +1
Is it possible to make a list of mist viewed posts based on this code?
I’m not sure if I understand, can you go into a little more detail.
Example:
Most viewed posts
Post title3 100 views
Post title1 50views
Post title2 10 views
Hi Bob,
Yes I had thought about doing something like this, ill fool around with the idea for a bit and post a snippet.
Just found this post.
http://www.moocr.com/blog/posts/2010/display-posts-views-count-without-plugin-in-wordpress.html
Did what the guy said. Doesn’t seem to work. Does it work in localhost?
It should work on local host fine, however you would need to reload the page to see any views. Don’t forget to place setPostViews within the loop within single.php. I tested it on wpsnipp.com to track views and it worked fine. What the snippet does is add a number to post meta and then increment that each time the single.php loads. What version of wordpress are you running?
Thanks.Just found out that I wasn’t implementing it correctly.
Cool glad you got everything working perfectly…
Do I have to set them manually?:/
Yes you would need to add this code to your wordpress templates manually.
Awesome share Chad. Thanks 😀