WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to show the post views for every post on a blog page (so in a loop).

I tried it with the following code in the functions.php:

  // function to count views.
function setAndViewPostViews($postID) {
    $count_key = 'views';
    $count = get_post_meta($postID, $count_key, true);
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        update_post_meta($postID, $count_key, $count);
    return $count; /* so you can show it */

Then in the loop function I used this code:

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

However, every post gets a count added every time the blog page is reloaded, strange thing is that the id is different for every post. How can I make this it will only count the every posts? And, if possible, how would I make it so that it only counts every individual views?

Thanks in advance!

Btw. I know there are a lot of plugins that do this, it's not my intention to use one, so please don't suggest a plugin.

share|improve this question
Have you looked at is_single() or is_singular() to restrict the counter updates? – birgire Nov 25 '13 at 19:32
None, I'm trying to put this in a plugin. I've put the <?php echo setAndViewPostViews(get_the_ID()); ?> under this while loop: <?php while ($query->have_posts()) : $query->the_post(); session_start(); – Trekdrop Nov 25 '13 at 19:46

Few remarks:

  • You should consider using a prefix on your meta key, for example lars_views, to minimize the risk of other plugins messing around with it.

  • If you want to hide it from the edit screen, you can use an underscore: _lars_views.

  • Consider wrapping the part of your code, that updates the counter, with if( is_single() ){...}. This will restrict it to single post views. More about this conditional tag in the Codex. If you have custom post types, consider is_singular().

  • You start the counter with 0, but I think it would be more accurate to start with 1 instead when you use is_single().

  • You can use update_post_meta() instead of add_post_meta(), if you want to simplify your code. Check out the Codex,

  • I would rather have a seperate function to show the counts and another one to update the counter via some hook. I think it's more flexible.

Hope this helps.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.