09
Jul
Display views count of particular post without using plugin in wordpress
- Category:
- Wordpress
Posted On : July 9, 2013
| No Comment
Several plugins are available for displaying Views Count for a particular post. So, from that you can know how many times a particular post has been viewed.
You can use plugins like “Post Views Count” or “WP-PostViews”, but also possible to complete this task with simple code in themes function.php file.
Code 1:
View Code PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | function wpb_track_post_views_count ($postid) { if ( !is_single() ) return; if ( empty ( $postid) ) { global $post; $postid = $post->ID; } wpb_set_post_views_count($postid); } add_action( 'wp_head', 'wpb_track_post_views_count'); function wpb_set_post_views_count($postid) { $count_key = 'wpb_post_views'; $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); } } //To keep the count accurate, lets get rid of prefetching remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); function wpb_get_post_views_count($postid){ $count_key = 'wpb_post_views'; $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'; } |
Code 2:
View Code PHP
1 | <!--?php echo wpb_get_post_views_count(get_the_ID()); ?--> |
Use above code wherever want to display number of views of particular post.(mostly in single.php file within loop)
Screenshot
- Tags: