Contents hide 1) Add View Count to Post 2) Get Views Count of Post 3) Display Post Views in WordPress Template In this tutorial, we see how to Display Post Views in WordPress using custom code without any plugin. All we going to do is create two simple methods which will be add a count and get count for the particular post. Add View Count to Post The first thing we need to do is to create a method in the functions.php file. The functionality will be like the method will accept an argument ID and by that ID the post_meta will be fetched for 'post_views_count'. Incase no post count is found then it will set to 0, and if post count is found then it will increment the post count. functions.php /** * function to count views. * @param {number} $postID : post ID */ 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); } } Get Views Count of Post The next thing will do is create a method in the same functions.php file which will retrieve the count of the user visits of a particular post.The functionality will be like the method will accept an argument ID and by that ID the post_meta will be fetched for 'post_views_count'. Incase if no post meta is found it will return β 0 Viewsβ and if itβs found then it will return count for e.x. 120 View. functions.php /** * function to get the post visits count. * @param {number} $postID : post ID * @return {string} return post visits count */ 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'; } Display Post Views in WordPress Template To display the post visits count we have to first add the count so whenever the single post is viewed it increments the count to the DB via our methods. you can add the method single.php if your template contains it or you can add in index.php file as it must be there. index.php / single.php <?php get_header(); ?> <?php if(have_posts()) : while (have_posts()) :the_post(); setPostViews(get_the_ID()); // Add the post count when the post is viewed ?> /* ...Your Blog Content... */ /* Display Where Ever You Want In Your Template */ <?= getPostViews(get_the_ID()) ?> /* ...Your Blog Content... */ <?php endwhile; endif; ?> Get More tutorials on WordPress Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: count visits, wordpress