Recently we got a request from a When Last Login customer that they would like to track who viewed their WordPress posts and would like to show the username with the time they viewed the article and thought this would be a great blog example for users to work from with custom code.
WordPress makes it easy to store data to posts by using the built in functions add_post_meta, get_post_meta and update_post_meta. These functions is what will handle adding, retrieving and saving data to WordPress posts.
Let’s Walk Through The Code
The code will consist of two main parts. 1) Saving data when a post is viewed in WordPress and 2) displaying the data in the posts admin page in WordPress. I am going to explain each function from top down and what the main parts of code do.
Saving Data To The WordPress Post
wll_save_when_viewed will only work for logged in users and if the type of post is ‘post’ and the user is not an administrator. You may adjust line 16 conditional statement to work for a Custom Post Type as well, including WooCommerce products. We then check if any data exists by calling the get_post_meta function as we want to update the existing data, if there is any. We then create an array that is set to
$time_array[$username] = time(). This will create data similar to
'my_username' => 12315490 which also means that if the user previously viewed the post, it would update the time they viewed the post instead of adding a new array entry. I almost always use update_post_meta as it will add data to the post meta if it doesn’t exist, and if it does just update it. The add_post_meta will always create a new entry into the post meta!
We hook into wp so that the post can be partly loaded, and make some of the data available as WordPress executes.
Showing The Saved Data In The Admin Area
wll_who_viewed_column_header function is self explanatory, this adds a new heading to the posts column in the WordPress dashboard with the title of ‘Who Last Viewed’.
wll_who_viewed_column function, is what adds data to that header. We retrieve the array from the posts and slice they array so we only show three users per post and sort it according to their time in descending order using PHP’s arsort function. Once the three values are sorted, we will loop through the values and print them to the screen and convert it to a human readable date and time in brackets (just to be fancy 😎 )
Now that you’ve learnt how to save and retrieve data inside of WordPress posts, you may save anything relating to the post. This is similarly how metabox data is stored, inside the post_meta table. Work through this example and see how you can improve on it, or save different data to a particular post or page using the *_post_meta functions.