Reputation: 31
WP_User_Query search by first & last name not working. Search returned only users where last_name = Doe. Filtering by first_name not work
$search_string_user = "John Doe";
$name_array = preg_split("/[\s,]+/", $search_string_user);
$users = new WP_User_Query(array(
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $name_array[0],
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $name_array[1],
'compare' => 'LIKE'
),
)
));
Upvotes: 3
Views: 1165
Reputation: 79
This does not address the original issue BUT this post does have the perfect title.
Modify the user search for Wordpress admin to include first name and last name and then return the results to the user table. No plugin!
Why this is not built-into Wordpress will we ever know?
Here is the link, this is also the source of the code: https://developer.wordpress.org/reference/hooks/pre_user_query/
This also, this one was not as helpful for me, plugins are not allowed were I worked before so I tend to shy away from them. How can I search by first name and/or last name among WordPress users?
I needed to use pre_user_query
to modify the wp_query that is passed into this action hook.
add_action( 'pre_user_query', function( $uqi ) {
global $wpdb;
$search = '';
if ( isset( $uqi->query_vars['search'] ) )
$search = trim( $uqi->query_vars['search'] );
if ( $search ) {
$search = trim($search, '*');
$the_search = '%'.$search.'%';
$search_meta = $wpdb->prepare("
ID IN ( SELECT user_id FROM {$wpdb->usermeta}
WHERE ( ( meta_key='first_name' OR meta_key='last_name' )
AND {$wpdb->usermeta}.meta_value LIKE '%s' )
)", $the_search);
$uqi->query_where = str_replace(
'WHERE 1=1 AND (',
"WHERE 1=1 AND (" . $search_meta . " OR ",
$uqi->query_where );
}
});
I searched Stack Overflow there were some weird not straight forward answers. This post had no answer and it kept showing up in my search. I searched hi and low for two hours and back and forth with a chatbot to learn how filters work in Wordpress. Then it gave me a relevant link to what I was trying to accomplish. Hopefully others will not have an issue finding this answer
Upvotes: 2