Are you looking for a way to track post and page views by user ID, date, and time? While there’s probably a plugin for this, we have created a quick code snippet that you can use to track post and page views by user ID, date, and time in WordPress.
First add wps_trackViewDates();
within the loop of your 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.
You can also 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 ‘strtotime’ in this case with 20+ minutes to expiry. View ‘strtotime’ for more options.
You can add a small snippet at the end called wps_getViewCounts(); that will simply return the number of unique post views.
Instructions:
All you have to do is add this code to your theme’s single.php file:
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); } }
To check if expiry is true, you can add the following code in your single.php file.
/* USAGE */ if(wps_trackViewDates() == true){ echo 'message when true'; }else{ echo 'message when false'; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 25 best tools for freelancers to scale a business and how to save partial form data in WordPress.
With this function how do you show to the admin the lasted post visited by every user?
Thanks
The function likely would need to be edited a bit in order to do this. That said, you may want to check out: https://www.isitwp.com/install-google-analytics-wordpress-site/
[…] Snippet courtesy of WP Snip […]
With this function how do you show to the admin the lasted post visited by every user?
Thanks