Easy way to Track Post Views Count without Plugins

Its always important to track the performance of any post or page and that can be easily done by tracking post views . Post views can be defined as the total number of views of a particular/single post get after its publication. There are some plugins that help to track pageviews but in this post I will share you method to track pageviews without any external plugins that help your website increasing website speed.

On WordPress website, we can track and display the all Post View Counter by doing the following steps:

Steps 1:Login to WordPress and go to Appearance>Theme Editor>>Function.php

After opening function.php file and copy the below code and paste

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

Steps 2: Set post views using single.php 

Following same path Appearance>Theme Editor>>single.php ,copy the single line code and paste on the file and save.

postviews-in-wordpress

setPostViews(get_the_ID());

Steps 3: Last now copy the following below code and paste where you want to show the pageviews

echo getPostViews(get_the_ID());

The above-mentioned methods shows a total number of views and user frequently visit the same post it will counts. So to get the unique number of views please proceed further:

You can collect unique visits by setting cookies and the IP address of visitor is trace and avoid the increase the page views when same user visits the given page . Please add the following code :

 

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{/*
* 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));

}
}

Leave a Comment