Simple Blog Post Counter WordPress Plugin

Date: Posted by: Karthick In: Wordpress

This is a simple blog post counter WordPress plugin example to get no of users visiting your blog post.

Create a file in plugin directory in WordPress, Copy the blow code and save, then open your single.php in theme directory,

/*
Plugin Name: Blog Post Counter
Plugin URI: http://www.sixvel.com/
Description: Simple Blog Post Counter Plugin
Version: 1.0
Author: Karthick
*/
function post_counter($post_ID)
{
$post_ID_enc = sha1(md5(md5($post_ID)));
session_start();
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
//Set the name of the Posts Custom Field.
$count_key = 'post_count_'.$post_ID;
//Returns values of the custom field with the specified key from the specified post.
$count = get_post_meta($post_ID, $count_key, true);
//If the the Post Custom Field value is empty.
if($count == ''){
$count = 0; // set the counter to zero.
//Delete all custom fields with the specified key from the specified post.
delete_post_meta($post_ID, $count_key);
//Add a custom (meta) field (Name/value)to the specified post.
add_post_meta($post_ID, $count_key, '0');
setcookie('ip_address', !empty($ip) ? $ip : 'none', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
setcookie('enc_id', !empty($post_ID) ? $post_ID_enc : 'none', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
return $count . ' View';
//If the the Post Custom Field value is NOT empty.
}else{
$count++; //increment the counter by 1.
//Update the value of an existing meta key (custom field) for the specified post.
if(($ip != $_COOKIE["ip_address"]) && $post_ID_enc == !$_COOKIE['enc_id']) {
update_post_meta($post_ID, $count_key, $count);
setcookie('ip_address', !empty($ip) ? $ip : 'none', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
setcookie('enc_id', !empty($post_ID) ? $post_ID_enc : 'none', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
}
//If statement, is just to have the singular form 'View' for the value '1'
if($count == '1'){
return $count . ' View';
}
//In all other cases return (count) Views
else {
return $count . ' Views';
}
}
}

Open up single.php in your themes directory, and call the below function and see the blog post counter starts directly in post pages

echo post_counter(get_the_ID());

311 Views

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

Affiliate Links

Advertisers

Categories

SEO Store

SEO Store

Archives

SEO Store

SEO Store

Tags

Advertisers

Top