Can’t Prevent Repeated Views and Exclude Bots(using HTTP user Agent) with PHP Post View Counter
I have been trying to make a Post View Counter for my WordPress Website. I intend to exclude Bots from being counted for which I used PHP user Agent and excluded most of the bots.
Then I wanted to ensure repeated visits are not counted so I built a Transient to do it.
But somehow it doesn’t work out well. Here’s my code.
function setPostViews($postID) {
$user_agents = array( 'GTmetrix', 'Googlebot', 'Bingbot', 'BingPreview', 'msnbot', 'slurp', 'Ask Jeeves/Teoma', 'Baidu', 'DuckDuckBot', 'AOLBuild' );
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$key = 'IP-' . $user_ip. '+'. $postID ;
$value = $user_ip;
$visited = get_transient($key);
$Bot=false;
foreach ( $user_agents as $agent ){
if ( strpos( $user_agent, $agent) ){
$Bot= true;
}
}
if($Bot=== false && (isset($_SERVER['HTTP_USER_AGENT']) && !preg_match('/BOT|google|yahoo|bing|spider|checker|discover|slurp|bot|crawl^$/i', $_SERVER['HTTP_USER_AGENT']))){
if(get_post_status($postID) === 'publish'){
if ( empty( $visited ) ) {
set_transient( $key, $value, '604800' );
$count_key = 'Creation_Views';
$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);
}
}
}
}
}
Obviously I called it as required. For a particular author on my site, I realized that he was getting exceptionally high views in no time.
So I used Google Analytics to see is he actually getting views. He got a 1000 views based on my plugin for a week, while Google Analytics showed less than 200..
I enquired and he said that he gets most of his traffic from WhatsApp.
What can be the possible ways to ensure only unique views are counted. And can there be bots coming from WhatsApp? If yes then how to exclude them
My goals is to ensure Only Actual Human visitors are counted. And only 1 visit by a device per day is counted. Please advice.
Leave an answer