Count post views without wordpress plugin

There are many wordpress plugin which will give you the post views using custom tables. But here using following code you can track the post views of your wp site.

Using external plugin, you can get the views and report but it will add more sql quries and extra load to your site. So I suggest use following code for getting the post views.

Count post views without wordpress plugin

Following code will track post views or count views of your wp site. You just need to copy and paste the following code into functions.php file first.


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

After adding the above code for tracking the post views you need to add following code into single.php file. Note: add following code inside the wp post loop.

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

For showing the post views you need to put following code in single.php file. Note: add following code inside the wp post loop.

<?php
          echo getPostViews(get_the_ID());
?>
Count post views without wordpress plugin
Count post views without wordpress plugin

Ref taken from: http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/