Home / functions.php / Track post and page views by user ID, date and time
  • How to Track post and page views by user ID, date and time

    track posts view code screenshot

    After an interesting conversation with a fan of wpsnipp, I come up with something to track unique post views for registered users. However this neat little snippet does a little more than that. First add wps_trackViewDates(); within the loop of your single.php template file. Once this has been added, the snippet will track the ID of the user that viewed an individual post along with the date and time it was viewed.

    I also decided to add an option for expiry that will compare expiry time from current time and return true while expiry time is less. This is quite useful if you wanted to display a customized message based on when each user viewed the post. You can see I use 'strtotime' in our case I added 20+ minutes to expiry. View 'strtotime' for more options.

    I also added a small snippet at the end called wps_getViewCounts(); that will simply return the number of unique post views. If you want a simpler snippet to just track post views grab this snippet that will let you track post views using post meta.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    function wps_trackViewDates(){
      global $post, $current_user;
      $data_key = '_utime';
      $utime = time();
      $data = get_post_meta($post->ID, $data_key, true);
      if(is_array($data)){
            if ( !in_array( $current_user->ID, $data ) ) {
                $data[$utime] = $current_user->ID;
                $data = array_unique($data, SORT_NUMERIC );
                update_post_meta($post->ID, $data_key, $data, false);
            }else{
                $saved_time = array_search($current_user->ID, $data);
                $expiry_time = strtotime("+20 minutes",$saved_time); // expires time
                if($expiry_time < $utime) return true;
            }
      }else{
        $data = array();
        $data[$utime] = $current_user->ID;
        add_post_meta($post->ID, $data_key, $data, false);
      }
    }
    function wps_getViewCounts(){
      global $post, $current_user;
      $data_key = '_utime';
      $data = get_post_meta($post->ID, $data_key, true);
      if(is_array($data)){ echo count($data); }
    }
    

    When checking to see if expiry is true you can use the following.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    /* USAGE */
    if(wps_trackViewDates() == true){
           echo 'message when true';
    }else{
           echo 'message when false';
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    get_post, add_post_meta, get_post_meta, update_post_meta, _n, wp,