Thêm cột user đăng nhập lần cuối WordPress

banner home FINAL 1050x121 1
huong dan su dung wordpress 2

Thêm cột user đăng nhập lần cuối WordPress như thế nào?

Hôm nay mình sẽ hướng dẫn làm thế nào để biết thời điểm cuối cùng người dùng đã đăng nhập vào website của bạn.

Bước 1. Lưu thời điểm cuối Login trong User Meta

Trước khi hiển thị ngày đăng nhập cuối cùng cho mỗi tài khoản người dùng, chúng ta phải thu thập nó trong mỗi lần người dùng đăng nhập vào website của bạn.

add_action( 'wp_login', 'misha_collect_login_timestamp', 20, 2 );

function misha_collect_login_timestamp( $user_login, $user ) {

update_user_meta( $user->ID, 'last_login', time() );

}

Bạn sao chép đoạn mã này đến tệp functions.php của giao diện hiện tại.

Đoạn code này cho phép WordPress bắt đầu lưu thời gian  vào trong bảng wp_usermeta mỗi khi một người dùng đăng nhập vào trang web của bạn.

Bước 2. Hiển thị thông tin trên trang All Users

add_filter( 'manage_users_columns', 'misha_add_last_login_column' );
add_filter( 'manage_users_custom_column', 'misha_last_login_column', 10, 3 );

function misha_user_last_login_column( $columns ) {

$columns['last_login'] = 'Last Login'; // column ID / column Title
return $columns;

}

function misha_last_login_column( $output, $column_id, $user_id ){

if( $column_id == 'last_login' ) {

$last_login = get_user_meta( $user_id, 'last_login', true );
$date_format = 'j M, Y';

$output = $last_login ? date( $date_format, $last_login ) : '-';

}

return $output;

}

Thêm xắp xếp (Sortable) cho cột

Bước này không bắt buộc nhưng khá hữu ích vì nó cho phép bạn xắp xếp thời gian nếu bạn muốn biết người dùng nào đang hoạt động tích cực ở gần đây.

add_filter( 'manage_users_sortable_columns', 'misha_sortable_columns' );

add_action( 'pre_get_users', 'misha_sort_last_login_column' );

function misha_sortable_columns( $columns ) {

return wp_parse_args( array(

'last_login' => 'last_login'

), $columns );
});
function misha_sort_last_login_column( $query ) {

if( !is_admin() ) {

return $query;

}
$screen = get_current_screen();
if( isset( $screen->id ) && $screen->id !== 'users' ) {

return $query;

}
if( isset( $_GET[ 'orderby' ] ) && $_GET[ 'orderby' ] == 'last_login' ) {
$query->query_vars['meta_key'] = 'last_login';

$query->query_vars['orderby'] = 'meta_value';
}
return $query;
} );

Lời kết

Chỉ với đoạn code đơn giản trên, bạn đã hiển thị thêm cột user đăng nhập lần cuối WordPress.

0/5 (0 Reviews)

# KHÁM PHÁ CÁC HASHTAG HÀNG ĐẦU

Theo dõi và cập nhật tin tức AZ9s thông qua các kênh truyền thông:

- Zalo Channel

- Facebook Channel

- Youtube Channel

banner home FINAL 1050x121 1
0 0 votes
Article Rating
Nhận thông báo qua Email
Nhận thông báo cho
guest

0 Comments
Inline Feedbacks
View all comments
0
Hãy để lại bình luận của bạn!x
()
x