默認情況下,在WordPress後臺的用戶列表中,隻能通過用戶名和郵箱搜索用戶。
如果你希望能通過搜索用戶的名字、姓氏和公開顯示名找到用戶,你可以將下面的代碼添加到當前主題的 functions.php 文件即可:
/* * 讓WordPress後臺用戶列表可以搜索名字、姓氏和公開顯示名 * From https://www.wpdaxue.com/wordpress-user-search.html */ //讓函數隻應用於WordPress後臺 if (is_admin()) { //通過鉤子掛載函數 add_action('pre_user_query', 'wpdaxue_pre_user_query'); } function wpdaxue_pre_user_query($user_search) { global $wpdb; $vars = $user_search->query_vars; if (!is_null($vars['search'])) { // 出於某種原因,搜索詞被星號包括,刪除它們 $search = preg_replace('/^\*/', '', $vars['search']); $search = preg_replace('/\*$/', '', $search); //搜索公開顯示名 if(!empty($search)){ $user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE '%". $search . "%')"; } //搜索名字和姓氏 $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " . "{$wpdb->users}.ID=m1.user_id AND (m1.meta_key='first_name')"; $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " . "{$wpdb->users}.ID=m2.user_id AND (m2.meta_key='last_name')"; $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s'", "%{$search}%", "%$search%"); $user_search->query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$names_where} OR ", $user_search->query_where); } return $user_search; } |
/*
* 讓WordPress後臺用戶列表可以搜索名字、姓氏和公開顯示名
* From https://www.wpdaxue.com/wordpress-user-search.html
*/
//讓函數隻應用於WordPress後臺
if (is_admin()) {
//通過鉤子掛載函數
add_action(‘pre_user_query’, ‘wpdaxue_pre_user_query’);
}
function wpdaxue_pre_user_query($user_search) {
global $wpdb;
$vars = $user_search->query_vars;
if (!is_null($vars[‘search’])) {
// 出於某種原因,搜索詞被星號包括,刪除它們
$search = preg_replace(‘/^\*/’, ”, $vars[‘search’]);
$search = preg_replace(‘/\*$/’, ”, $search);
//搜索公開顯示名
if(!empty($search)){
$user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE ‘%". $search . "%’)";
}
//搜索名字和姓氏
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " .
"{$wpdb->users}.ID=m1.user_id AND (m1.meta_key=’first_name’)";
$user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " .
"{$wpdb->users}.ID=m2.user_id AND (m2.meta_key=’last_name’)";
$names_where = $wpdb->prepare("m1.meta_value LIKE ‘%s’ OR m2.meta_value LIKE ‘%s’", "%{$search}%", "%$search%");
$user_search->query_where = str_replace(‘WHERE 1=1 AND (‘, "WHERE 1=1 AND ({$names_where} OR ", $user_search->query_where);
}
return $user_search;
}
如果以上的代碼仍不能滿足你的要求,那你可以試試 Better User Search 外掛,它可以讓你的用戶列表頁面支援搜索所有字段。