Created
October 31, 2018 15:15
-
-
Save nfsarmento/78afee684e86b222161a78efb8d23415 to your computer and use it in GitHub Desktop.
Admin user page custom column - Print User Web Visits Column Value
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
/* | |
* Admin user page custom column - Print User Web Visits Column Value | |
* | |
* https://www.nuno-sarmento.com | |
* | |
*/ | |
class NSLogin_Counter { | |
public function init() { | |
add_action( 'wp_login', array( $this, 'count_user_login' ), 10, 2 ); | |
add_filter( 'manage_users_columns', array( $this, 'add_stats_columns' ) ); | |
add_filter( 'manage_users_custom_column', array( $this, 'fill_stats_columns' ), 10, 3 ); | |
} | |
/** | |
* Save user login count to Database. | |
* | |
* @param string $user_login username | |
* @param object $user WP_User object | |
*/ | |
public function count_user_login( $user_login, $user ) { | |
$count = get_user_meta( $user->ID, 'sp_login_count', true ); | |
if ( ! empty( $count ) ) { | |
$login_count = get_user_meta( $user->ID, 'sp_login_count', true ); | |
update_user_meta( $user->ID, 'sp_login_count', ( (int) $login_count + 1 ) ); | |
} | |
else { | |
update_user_meta( $user->ID, 'sp_login_count', 1 ); | |
} | |
} | |
/** | |
* Add the login stat column to WordPress user listing | |
* | |
* @param string $columns | |
* | |
* @return mixed | |
*/ | |
public function add_stats_columns( $columns ) { | |
$columns['login_stat'] = __( 'Login Count' ); | |
return $columns; | |
} | |
/** | |
* Fill the stat column with values. | |
* | |
* @param string $empty | |
* @param string $column_name | |
* @param int $user_id | |
* | |
* @return string|void | |
*/ | |
public function fill_stats_columns( $empty, $column_name, $user_id ) { | |
if ( 'login_stat' == $column_name ) { | |
if ( get_user_meta( $user_id, 'sp_login_count', true ) !== '' ) { | |
$login_count = get_user_meta( $user_id, 'sp_login_count', true ); | |
return "<strong>$login_count</strong>"; | |
} | |
else { | |
return __( '0' ); | |
} | |
} | |
return $empty; | |
} | |
/** | |
* Singleton class instance | |
* @return NSLogin_Counter | |
*/ | |
public static function get_instance() { | |
static $instance; | |
if ( ! isset( $instance ) ) { | |
$instance = new self(); | |
$instance->init(); | |
} | |
return $instance; | |
} | |
} | |
NSLogin_Counter::get_instance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment