Hours
Minutes
Seconds

35% Flat Discount on Quix Licenses. Buy Pro

How To Track & Display WordPress Post Views Without Any Plugin

How To Track & Display WordPress Post Views Without Any Plugin

Hopefully, you have already seen some blogs use displaying the total view number for every post to prove their visitors engagement, and now you may want to know how it is done?

Do you want to know how many times a particular post has been viewed and as well as want to show the result to your viewers? In this tutorial, I will show you step by step how you can display the total number of views of a particular post without using any plugin.

This is a three simple steps process and its pretty much easy to follow.

First Step

Add this codes from the following block in your themes function.php file. It will configure your theme to enhance this functionality.


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

The following code will count the views when someone refreshes or view the post, and it won't discriminate between visitors.

Second Step:

Now add the following line of code in your single.php file within the loop. It will track the views and set the views of each post.

setPostViews(get_the_ID());

Third Step:

Now at the last step use the following line of code where you want to display the view number inside the loop. It will get the post view number from the last step where you call the set function to track the post views.

echo getPostViews(get_the_ID());

The following image manifests that the code works finely on my local server:

Kudos to Wpsnipp for creating such useful snippet.

Conclusion

Hope you have found this article helpful. Let us know your opinion or questions if any through the comment section in below.

Comments (1)

This comment was minimized by the moderator on the site

Thanks for the great script. What i need to modify if i would like to only count and display the daily views per post?

There are no comments posted here yet

Leave your comments

  1. Posting comment as a guest. Sign up or login to your account.
Attachments (0 / 3)
Share Your Location