Last active
February 27, 2019 20:42
-
-
Save adamwalter/a676426ac2919238b798687ea89c1bdb to your computer and use it in GitHub Desktop.
Captures user login timestamp and saves to user meta in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Captures user login timestamp and saves to user meta | |
* | |
* @param string $user_login Username of user logging in | |
* @param object $user WP_User object of user logging in | |
*/ | |
add_action('wp_login', function($user_login, $user) { | |
$timestamp = date('Y-m-d H:i:s', current_time('timestamp', 1)); | |
update_user_meta($user->ID, 'last_login', $timestamp); | |
}, 10, 2); | |
/** | |
* Adds Last Login column to user list in wp-admin | |
*/ | |
add_filter('manage_users_columns', function($column) { | |
$column['last_login'] = 'Last Login'; | |
return $column; | |
}); | |
/** | |
* Populates Last Login column in user list in wp-admin | |
* | |
* @param string $output Custom column output | |
* @param string $column_name Column name | |
* @param int $user_id ID of the currently-listed user | |
*/ | |
add_filter('manage_users_custom_column', function($output, $column_name, $user_id) { | |
switch ($column_name) { | |
case 'last_login': | |
if ($last_login = get_the_author_meta('last_login', $user_id)) { | |
$last_login = get_date_from_gmt($last_login, get_option('date_format') . ' \a\t ' . get_option('time_format')); | |
return esc_html($last_login); | |
} else { | |
return 'Unknown'; | |
} | |
break; | |
default: | |
} | |
return $output; | |
}, 10, 3); | |
/** | |
* Styles Last Login column in user list in wp-admin | |
*/ | |
function vtl_last_login_column_style() { | |
echo '<style type="text/css">.column-last_login { width: 12%; }</style>'; | |
} | |
add_action('admin_print_styles-users.php', 'vtl_last_login_column_style'); | |
add_action('admin_print_styles-site-users.php', 'vtl_last_login_column_style'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment