X

How To Track Post Views Without a Plugin Using Post Meta

Snippets by IsItWP

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.

Comments   Leave a Reply

  1. Any idea of how to use this with a Custom Post Type?

  2. awesome stuff exactly what I was looking for?

    1. cool glad to hear you like the snippet enjoy.

      1. Likewise can we count the number of images uploaded on the wordpress site, I am sure we can.. any clue?

  3. Example of Bob is possible?

    Most viewed posts
    Post title3 100 views
    Post title1 50views
    Post title2 10 views

  4. 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.. ??

    1. 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.

  5. how to remove the  “Views” word ?                       

    1. Hi Joj,
      You will see on line 09    return $count.’ Views’;
      replace that line with the bellow and that is it.
      return $count;

  6. 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;
    }

    1. Thanks drew very cool.

    2. 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?

      1. Oops. Wasn’t logged in as admin during testing. (facepalm)

        1. Glad to hear you got things working.

  7. Gabriel Merovingi August 6, 2011 at 10:51 pm

    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.

    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 ?

      1. Gabriel Merovingi August 7, 2011 at 12:35 am

        Its on my localhost. Its really odd but might be just some browser thing. Thanks for a nice little snippet though!

      2. 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

        1. 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.

    2. 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:                                ( )       

      1. Sorry, I copy-pasted the code into the reply box. Shortlinkoed via codepad, check it there : )
        http://codepad.org/QOUWc3XB

  8. 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.

    1. 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.

  9. Site Review: WordPress Code Snippets | ButlerBlog July 28, 2011 at 11:29 pm

    […] 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 […]

  10. tasarhane designhouse July 24, 2011 at 10:43 am

    hey, its cool..
    thanks a lot.

    1. Cool glad you like the snippet. 

  11. amazing, thank you!

    1. no problem @4f9649a2dc0c5d186623a62544564bfe:disqus glad you like the snippet!

  12. 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!

    1. 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. 

      1. 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 🙂

    2. hello, As i know W3TC has a “Ignored query stems” to filter out some functions from cache.

  13. 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

    1. 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/

  14. Andrei Oprinca May 28, 2011 at 2:10 pm

    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.

    1. 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.

  15. 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?

    1. 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…

      1. Yeah it’s in the single.php in the loop

        1. 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. 

      2. Samuel Francisco July 4, 2011 at 8:28 am

        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.

        1. 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?

        2. Chris (4O1! Creative) May 2, 2012 at 9:09 pm

          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); 

          1.  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,

    2. 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,

    3.   @e4fcff6cc58dc5e1b2ab556d9cdb2cb2:disqus you need to use the getPostViews() function when you want to display post views and setPostViews() on the single.php.

  16. Helpful Tips, Hacks and Tutorials about WordPress - Wordpress Arena April 13, 2011 at 12:06 pm

    […] Track post views without a plugin using post meta […]

  17. Afficher le nombre de visite par article sans extension en utilisant la balise meta | Un Blog Presque Parfait April 9, 2011 at 9:22 am

    […] Via : lien […]

  18. This technique won’t work with cache plugin. I would like using WP-PostViews plugin as it provides a better compatibility with cache plugin.

    1. This is true, it does not play nice with cache plugins. However as a quick snippet to track views it works quite well.

  19. 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.

    1. Ahh good call Daniel, you could do that.

  20. 20 More WordPress Code Snippets and Hacks March 28, 2011 at 4:02 am

    […] 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 […]

  21. 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 ?

    1. Hi Alec,
      I just finished a post for that yesterday and will be posting it in about an hour.

    2. First time i visit your site, and already my hero! +1

  22. Is it possible to make a list of mist viewed posts based on this code?

    1. I’m not sure if I understand, can you go into a little more detail.

    2. Example:
      Most viewed posts
      Post title3 100 views
      Post title1 50views
      Post title2 10 views

    3. Hi Bob,
      Yes I had thought about doing something like this, ill fool around with the idea for a bit and post a snippet.

  23. 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?

    1. 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?

    2. Thanks.Just found out that I wasn’t implementing it correctly.

    3. Cool glad you got everything working perfectly…

  24. Do I have to set them manually?:/

    1. Yes you would need to add this code to your wordpress templates manually.

  25. Awesome share Chad. Thanks 😀

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!