Track post and page views by user ID, date and time

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.

function wps_trackViewDates(){
  global $post, $current_user;
  $data_key = '_utime';
  $utime = time();
  $data = get_post_meta($post->ID, $data_key, true);


        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);
            $saved_time = array_search($current_user->ID, $data);
            $expiry_time = strtotime("+20 minutes",$saved_time); // expires time
            if($expiry_time < $utime) return true;

    $data = array();
    $data&#91;$utime&#93; = $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.

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

Comments  Leave a Reply

  1. Learn how to track WordPress Page Views by User ID and Time June 8, 2015 at 7:15 am

    […] Snippet courtesy of WP Snip […]

  2. With this function how do you show to the admin the lasted post visited by every user?


Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!