The Simplest WordPress User Access Log Ever

Those of use who develop using pods often find we use it for everything. So here’s a quick tip on using PodsCMS to create a custom user access log.

Step 1: Set up the Pod

I’m assuming you’ve already installed/activate both the PodsCMS and Pods UI plugins. If not, please do so before starting.

Create a new Pod called “logins”.

By default each pod is created with a name and slug field. We’re going to use the name field but you can delete the slug field.

Then you’ll need to create a field for “date”. Of course, Pods stores the date any entry is created in a field called “created” which you can access from within Pods Templates. But it still makes sense to have a date field in the Pod itself, if nothing else for the sake of a clear data model.

So once you have added the date field your Pod will look like this:

Step 2: Add function

Now just add the following code to your functions.php file.

add_action('set_logged_in_cookie','mpv_add_access_log_entry');
function mpv_add_access_log_entry($user) {
$user = explode('|',$user);
$log = new PodAPI(); 
$params = array('datatype'=>'logins');
$params['columns'] = array('name'=>$user[0],'date'=>date('Y-m-d H:i:s'));
$log->save_pod_item(pods_sanitize($params));
}

This function uses the Pod API to insert a row in the logins table. Alternatively you can use the $wpdb class and do something like this:

global $wpdb;
$wpdb->insert($wpdb->prefix.'pod_tbl_logins',array('name'=> $user[0],'date'=> date('Y-m-d H:i:s')));

The only trouble with going this route is that in order to use the pods admin interface to manage the data, you’ll also need to add a row to the wp_pod table. This will change with Pods 2.0 so there’s no need to demonstrate. But I strongly recommend using the PodsAPI class as it will make sure to implement best practices and in 2.0 it will use the $wpdb class anyway.

So that’s it. To create an exportable report of the logins just install the “Exports and Reports” plugin. Or you can use PodsUI to create a custom interface.

Have fun.