Do you want to count and display the total view number of a particular blog post on your WordPress website, please follow the below steps.
There are three simple steps and it’s pretty much easy to follow.
Step 1:
Add these codes 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);
Step 2:
Now in the second step add the following code into your single.php file within the loop. This will track the views and display into every single post.
setPostViews(get_the_ID());
Step 3:
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());
I hope this article will help you to display post view count.
Thanks & enjoy happy coding.