0

I want to get the total number of results after searching WordPress users by role and a string that matches the user name.

What I tried so far:

$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();

But it returns 0 everytime.

Note:

Perhaps it can be done by:

$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$auth_count= count(get_users($args));

or by querying with

global $wpdb;

But is there any more resource friendly method?

2
  • Your first code looks ok to me. Docs don't specify but perhaps role is case sensitive, try 'Author' if that's what your role is called. And are you 100% sure you have users that will match $search_txt. I'm not sure what else would explain getting zero results unless it really is zero results for your search ;-)
    – mozboz
    Jul 29, 2020 at 18:37
  • Nopes... Neither 'Author' nor 'author' works. Its the same. I'm searching with $search_txt='sun', and there are users with names like 'Sunita', 'Sunheri'.
    – sariDon
    Jul 29, 2020 at 18:54

2 Answers 2

0

Adding this as an answer here for reference for anyone searching for WP_User_Query stuff:

As per the docs The search field on WP_User_Query uses * for wildcard text search, and will search on login, nicename, email and URL, unless specified otherwise.

E.g. to match any name containing bob you need:

$args = array(
    'search'         => '*bob*'
);

$user_query = new WP_User_Query( $args );
0

This worked:

$search_txt replaced by esc_attr($search_txt).'*':

$args= array('echo'=>false, 'role' => 'author', 'search'=>esc_attr($search_txt).'*');
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();
2
  • Ah yes, well spotted. The docs say 'search (string) - Searches for possible string matches on columns. Use of the * wildcard before and/or after the string will match on columns starting with*, ending with, or *containing the string you enter.'
    – mozboz
    Jul 29, 2020 at 19:29
  • Thank you @mozboz
    – sariDon
    Jul 29, 2020 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.