Categories: wordpress

HOW TO SHOW NUMBER OF VIEW (VIEW COUNT) IN WORDPRESS? [for wordpress developer]

First of all you ned to set post view count using post meta.
Use the following code to set post

function setPostViews($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
}

The second Process is to add function to show the total view in the post
you can use the follwing code in function.php

function pp_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";
}
return $count;
}

The next step is to display the count in the post. In the post loop (ie. in single.php) you have to add the following code to display the number of post view count.

<?php pp_getPostViews(get_the_ID()); ?>

Now the last and the most important step is to put the following code for increasing the count in single.php

<?php setPostViews(get_the_ID()); ?>
jaminrai