WordPress 技巧:增强 WordPress 用户搜索

2023-04-15 11:19:11 浏览数 (1)

WordPress 后台的用户搜索默认是基于用户的 user_login 和 user_nicename 进行搜索的。有时候我们想增强 WordPress 用户的搜索,希望还能支持通过 display_name, nickname, user_email 进行检索,可以通过在当前主题的 functions.php 文件中添加下面这段代码实现:

代码语言:javascript复制
<?php
/*
Plugin Name: 增强 WordPress 用户搜索
Plugin URI: http://blog.wpjam.com/m/enhance-wordpress-user-query/
Description: WordPress 技巧:增强 WordPress 用户搜索
Version: 0.1
Author: Denis
Author URI: http://blog.wpjam.com/
*/
add_action( 'pre_user_query', 'wpjam_enhance_user_query', 9 );
function wpjam_enhance_user_query($query){
	
    if(!empty($query->query_vars['search'])){
        global $wpdb;
        $keyword = $query->query_vars['search'];
        $keyword = str_replace('*','',$keyword);
        $query->query_where = $wpdb->prepare(" WHERE 1=1 AND (user_login LIKE %s OR user_email LIKE %s OR user_nicename LIKE %s OR display_name LIKE %s OR UM.meta_value LIKE  %s) AND UM.meta_key='nickname'","%".$keyword."%","%".$keyword."%","%".$keyword."%","%".$keyword."%","%".$keyword."%");
        $query->query_fields .= " ,$wpdb->users.display_name, UM.meta_value as nickname";
        $query->query_from .= " left join $wpdb->usermeta UM on ($wpdb->users.ID=UM.user_id) ";
    }
}

0 人点赞