将下面的代码添加到主题的 functions.php 即可
//WordPress 后台用户列表显示用户昵称
add_filter(‘manage_users_columns’, ‘add_user_nickname_column’);
function add_user_nickname_column($columns) {
$columns[‘user_nickname’] = ‘昵称’;
return $columns;
}
add_action(‘manage_users_custom_column’, ‘show_user_nickname_column_content’, 20, 3);
function show_user_nickname_column_content($value, $column_name, $user_id) {
$user = get_userdata( $user_id );
$user_nickname = $user->nickname;
if ( ‘user_nickname’ == $column_name )
return $user_nickname;
return $value;
}
如果你需要去除“姓名”这一栏,在上面的第 7 行下面添加以下代码即可:
unset($columns[‘name’]); //移除“姓名”这一栏
让后台用户列表支持搜索昵称
默认情况下,WordPress后台只能通过用户名、邮箱进行用户搜索,如果要通过昵称搜索,只需要添加下面的代码到主题的 functions.php 文件即可:
function wpkj_extend_user_search( $u_query ){
// 确保代码仅应用于用户搜索
if ( $u_query->query_vars[‘search’] ){
$search_query = trim( $u_query->query_vars[‘search’], ‘*’ );
if ( $_REQUEST[‘s’] == $search_query ){
global $wpdb;
// 添加昵称搜索查询语句
$u_query->query_from .= ” JOIN {$wpdb->usermeta} fname ON fname.user_id = {$wpdb->users}.ID AND fname.meta_key = ‘nickname'”;
// 设置可搜索的字段
$search_by = array( ‘user_login’, ‘user_email’, ‘fname.meta_value’ );
// 应用到搜索
$u_query->query_where = ‘WHERE 1=1’ . $u_query->get_search_sql( $search_query, $search_by, ‘both’ );
}
}
}
add_action(‘pre_user_query’, ‘wpkj_extend_user_search’);