Add post views feature without using a plugin

I was trying to add view Counts for Posts in to one client's blog site. I didn't want to use any plugin . So, i was looking for alternative way and finally comes up with this solution. Got this solution from Kevin Chart post.

The first thing to do is to create the functions. Paste the code below into your functions.php file.

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

Then, paste the code below within the single.php within the loop:

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

Finally, paste the snippet below anywhere within the template where you would like to display the number of views:

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

If you have any issues, feel free to comment here and let us know .

Thank you.

Mahi
Written by

Mahi

No Description found!

Have something to say? Cancel Reply

Your email address will not be published.

Table of Contents