settings = $settings; $this->users(); } private function users() : void { $add = (array) $this->settings->get( 'tables.users.add', [] ); $remove = (array) $this->settings->get( 'tables.users.remove', [] ); if ( $add === [] && $remove === [] ) { return; } add_filter( 'manage_users_columns', function ( array $columns ) use($add, $remove) : array { foreach ( $remove as $column ) { unset($columns[$column]); } foreach ( $add as $column ) { if ( $column === 'registration_date' ) { $columns['registration_date'] = __( 'Registration date', 'featherdash' ); } if ( $column === 'last_login' ) { $columns['last_login'] = __( 'Last login', 'featherdash' ); } } return $columns; } ); add_filter( 'manage_users_custom_column', [$this, 'renderUserColumn'], 10, 3 ); add_filter( 'manage_users_sortable_columns', function ( array $columns ) use($add) : array { if ( in_array( 'registration_date', $add, true ) ) { $columns['registration_date'] = 'registered'; } if ( in_array( 'last_login', $add, true ) ) { $columns['last_login'] = 'last_login'; } return $columns; } ); if ( in_array( 'last_login', $add, true ) ) { add_action( 'pre_get_users', [$this, 'orderUsersByLastLogin'] ); } } /** * @param mixed $output * @param mixed $column * @param mixed $userId */ public function renderUserColumn( $output, $column, $userId ) : string { $column = (string) $column; $userId = (int) $userId; $format = $this->dateTimeFormat(); if ( $column === 'registration_date' ) { $user = ( $userId > 0 ? get_userdata( $userId ) : false ); if ( $user === false ) { return '—'; } $timestamp = strtotime( (string) $user->user_registered ); return ( $timestamp === false ? '—' : wp_date( $format, $timestamp ) ); } if ( $column === 'last_login' ) { $lastLogin = get_user_meta( $userId, 'last_login', true ); if ( !is_string( $lastLogin ) || $lastLogin === '' ) { return '—'; } $timestamp = strtotime( $lastLogin . ' UTC' ); return ( $timestamp === false ? '—' : wp_date( $format, $timestamp ) ); } return ( is_string( $output ) ? $output : '' ); } public function orderUsersByLastLogin( WP_User_Query $query ) : void { if ( !function_exists( 'get_current_screen' ) ) { return; } $screen = get_current_screen(); if ( $screen === null || $screen->id !== 'users' ) { return; } if ( $query->get( 'orderby' ) !== 'last_login' ) { return; } $order = strtoupper( (string) $query->get( 'order' ) ); if ( !in_array( $order, ['ASC', 'DESC'], true ) ) { $order = 'ASC'; } $query->set( 'meta_query', [ 'relation' => 'OR', 'featherdash_last_login' => [ 'key' => 'last_login', 'compare' => 'EXISTS', ], [ 'key' => 'last_login', 'compare' => 'NOT EXISTS', ], ] ); $query->set( 'orderby', 'featherdash_last_login' ); $query->set( 'order', $order ); } private function dateTimeFormat() : string { return (string) get_option( 'date_format' ) . ' ' . (string) get_option( 'time_format' ); } }