Add Post View Counter Without Plugin in WordPress

To show the popularity of a post in WordPress we use post view counter.  So that user can understand the popularity of certain post. If you want to use a plugin then just go to WordPress plugin directory and search for post view counter and you will get many free plugins to show post view counter. But we will show you how to add post view counter without plugin in WordPress in three simple steps.

set-post-view-in-wordpress

Step 1:

At first add the following function to your current theme’s functions.php:

[html]
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 So Far.’;
}

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

add_filter(‘manage_posts_columns’, ‘posts_column_views’);
add_action(‘manage_posts_custom_column’, ‘posts_custom_column_views’,5,2);
function posts_column_views($defaults){
$defaults[‘post_views’] = __(‘Views’);
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === ‘post_views’){
echo getPostViews(get_the_ID());
}
}
[/html]

Step 2:

Then add the following code inside while loop in single.php file.

[php]<?php setPostViews(get_the_ID()); ?>[/php]

set-post-view1

Step 3:

Now place where you want to show the no. of views. We have set it also in single post:

[php]<?php echo getPostViews(get_the_ID()); ?>[/php]

set-post-view2

Author: mytutorialguru

Share This Post On

Submit a Comment

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