Skip to content

Add post views feature without using a plugin

Mahi

Mahi

  • Snippets
Human Written

1 mins read

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.

Get Fresh
Updates Every Week

Get access to exclusive guides, tips, updates, ebooks, and more.

WAIT! Don’t Miss Our Biggest Sale of the Year!

BlackFriday

EarlyDeals

Save Up To

81%

on weDevs Products

Hurry! This massive deal disappears when the timer runs out.

00Days00Hour00Min00Sec
Claim Yours & Save Up To 81%