• Posted: 2011-07-22
  • Author: Filip Stefansson
  • Tags:

Post views without plugin

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
<?php
// function to display number of posts.
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 to 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);
    }
}


// Add it 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());
    }
}
?>

Instructions:

There are lots of plugins that keep count of your posts views, but they all tend to be quite advanced and do a lot more than you might need(which is true for most plugins in general too).

This simple, yet brilliant snippet posted by Kevin Chard over at WP-Snipp does exactly what we need, and nothing more. Follow the steps below to count and display the number of views a post has.

Add the snippet to functions.php and follow these instruction:

Add this to single.php, and make sure you paste in inside the loop.

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

Lastly, to display the number of views a post has, just add this where you want it to be displayed:

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

Related links:
http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/
Share this snippet

If you like this snippet, share it with friends!