Do you want to know on your WP website how many times a particular/single post has been viewed and as well as want to show the all view count result to your viewers on your website’s post? So in this page/tutorial, I will show you how you can easily track and display the total number of views of a particular/single post without using any WP plugin.
Specially on your WP Website/Blog’s single post (Front-end), you can track and display the all Post View Counter by doing the following method: Just open the “functions.php” file from located in your installed theme’s folder, and add (copy and paste) the following all code and save the file.
The First Step:
Just add (copy and paste) the codes from the following given box direct in your installed themes folder’s function.php file.
$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 Second Step:
Now add (copy and paste) the following small line of code in your “single.php” file within the loop. It will track the views and set the views of every single post.
The Third Step:
Now the last step add (copy and paste) the following code where you want to display the view number inside the loop.
Extra Tips:
On the above given codes it counts multiple views from the same person, so when user/visitor refresh the same page or go back to it, its counting them each as separate views. So in this case how do track views by only individual users?
Simply you can use the cookie for individual user by user’s IP address.
For 1st time visit add the count and set cookie. If cookie exit then no need to increase the count.
$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{/*
* Check the cookie is exist or not.
* If not the set cookie for some time interval and
* increase the count
*/
if(!isset($_COOKIE[‘wpai_visited_ip’]))$count++;
update_post_meta($postID, $count_key, $count);// Get IP address
$visit_ip_addr = $_SERVER[‘REMOTE_ADDR’];
// Set the cookie
setcookie(‘wpai_visited_ip’, $visit_ip_addr, time()+ (60 * 1));
}
}
In the end
I hope you have found this article helpful. Let us me your opinion or questions if any through the comment form in below or use this form to ask your question.