How To Track & Display WordPress Post Views With Plugin Without Plugin
In this tutorial, I will show you step by step how you can display the total number of views of a particular post without using any plugin.
First Step:
Add this codes from the following block in your themes function.php file. It will configure your theme to enhance this functionality.
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) { $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); } } // Remove issues with prefetching adding extra views remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
Second Step:
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.
setPostViews(get_the_ID());
Third Step:
Now at the last step use the following line of code where you want to display the view number inside the loop. It will get the post view number from the last step where you call the set function to track the post views.
echo getPostViews(get_the_ID());