How to get post views count without plugin

Many WordPress use WP-PostView+ plugin to track post views. But there is a simple solution to add post views counter function into WordPress theme without any plugins. This tutorial will show you how to track post views in your theme.

1. Add the core functions into “function.php” file.

Use the following functions to track post views.

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

2. Track views

In order to tack ever views, we need to activate the core function every time users open a single page. So place the following snippet to single.php and make sure placed it inside the loop.

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

3. Get views statics

Paste the following snippet to where you want to show the views number.

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

After that, you can stop post view statistics plugins in your WordPress dashboard. Enjoy it!

Leave a Reply

Your email address will not be published. Required fields are marked *