Jheben

Simple to display WordPress post view count without a plugin

May 16th, 2020
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.94 KB | None | 0 0
  1. Add this code your functions.php
  2.  
  3. PHP
  4.  
  5. // function to display number of posts.
  6. function getPostViews($postID){
  7.     $count_key = 'post_views_count';
  8.     $count = get_post_meta($postID, $count_key, true);
  9.     if($count==''){
  10.         delete_post_meta($postID, $count_key);
  11.         add_post_meta($postID, $count_key, '0');
  12.         return "0 View";
  13.     }
  14.     return $count.' Views';
  15. }
  16.  
  17. // function to count views.
  18. function setPostViews($postID) {
  19.     $count_key = 'post_views_count';
  20.     $count = get_post_meta($postID, $count_key, true);
  21.     if($count==''){
  22.         $count = 0;
  23.         delete_post_meta($postID, $count_key);
  24.         add_post_meta($postID, $count_key, '0');
  25.     }else{
  26.         $count++;
  27.         update_post_meta($postID, $count_key, $count);
  28.     }
  29. }
  30.  
  31.  
  32.  
  33. Add this code to your single.php file
  34. <?php setPostViews(get_the_ID()); ?>
  35.  
  36.  
  37. Add this code for display post counter
  38. <?php echo getPostViews(get_the_ID()); ?>
Advertisement
Add Comment
Please, Sign In to add comment