If you want to keep real-time track of your WordPress post views by user IP then you can use this code. Below code snippet will gives stats for each post.
This is a three simple steps process and its pretty much easy to follow.
Add below codes in your themes function.php file.
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) {
//check if user not administrator, if so execute code block within
if( !current_user_can('administrator') ) {
$user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
$key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
$value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
$visited = get_transient($key); //get transient and store in variable
//check to see if the Post ID/IP ($key) address is currently stored as a transient
if ( false === ( $visited ) ) {
//store the unique key, Post ID & IP address for 12 hours if it does not exist
set_transient( $key, $value, 60*60*12 );
// now run post views function
$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);
}
}
}
}
Now add the following line of code in your single.php file within the loop. It will track the views and set the views of each post.
<?php setPostViews(get_the_ID()); ?>
Now at the last step use the following line of code where you want to display the view number inside the loop.
<?php echo getPostViews(get_the_ID()); ?>
If you want to Add Post View Column to the Posts Screen. use below codes in your themes function.php file
// ADD NEW COLUMN HEADING
function AB_post_views_columns_head($defaults) {
$defaults['ab_post_views'] = 'View Counts';
return $defaults;
}
add_filter('manage_posts_columns', 'AB_post_views_columns_head');
// SHOW VIEWS COUNT
function AB_post_views_columns_content($column_name, $post_ID) {
if ($column_name == 'ab_post_views') {
$post_views_counts = getPostViews(get_the_ID());
if ($post_views_counts) {
echo $post_views_counts;
}
}
}
add_action('manage_posts_custom_column', 'AB_post_views_columns_content', 10, 2);
Last Update on:March 5th, 2023 at 5:19 pm