Advertisement
meetsos

Pieter Goosen Post Views

Nov 15th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.02 KB | None | 0 0
  1. if ( ! function_exists( 'pietergoosen_get_post_views' ) ) :
  2.  
  3. function pietergoosen_get_post_views($postID){
  4.     $count_key = 'post_views_count';
  5.     $count = get_post_meta($postID, $count_key, true);
  6.     if($count==''){
  7.         delete_post_meta($postID, $count_key);
  8.         add_post_meta($postID, $count_key, '0');
  9.         return 0;
  10.    }
  11.    return $count;
  12. }
  13.  
  14. endif;
  15.  
  16. // function to count views.
  17. if ( ! function_exists( 'pietergoosen_update_post_views' ) ) :
  18.  
  19. function pietergoosen_update_post_views($postID) {
  20.     if( !current_user_can('administrator') ) {
  21.         $user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
  22.         $key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
  23.         $value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
  24.         $visited = get_transient($key); //get transient and store in variable
  25.  
  26.         //check to see if the Post ID/IP ($key) address is currently stored as a transient
  27.         if ( false === ( $visited ) ) {
  28.  
  29.             //store the unique key, Post ID & IP address for 12 hours if it does not exist
  30.            set_transient( $key, $value, 60*60*12 );
  31.  
  32.             // now run post views function
  33.             $count_key = 'post_views_count';
  34.             $count = get_post_meta($postID, $count_key, true);
  35.             if($count==''){
  36.                 $count = 0;
  37.                 delete_post_meta($postID, $count_key);
  38.                 add_post_meta($postID, $count_key, '0');
  39.             }else{
  40.                 $count++;
  41.                 update_post_meta($postID, $count_key, $count);
  42.             }
  43.         }
  44.     }  
  45. }
  46.  
  47. endif;
  48.  
  49. remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
  50.  
  51. // initialzing
  52. function wpb_track_post_views2 ($post_id) {
  53.     if ( !is_single() ) return;
  54.     if ( empty ( $post_id) ) {
  55.         global $post;
  56.         $post_id = $post->ID;    
  57.     }
  58.     pietergoosen_update_post_views($post_id);
  59. }
  60. add_action( 'wp_head', 'wpb_track_post_views2');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement