admin管理员组

文章数量:1327849

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?

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?

Share Improve this question edited Jul 29, 2020 at 18:55 sariDon asked Jul 29, 2020 at 18:28 sariDonsariDon 2651 gold badge2 silver badges18 bronze badges 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 Commented 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 Commented Jul 29, 2020 at 18:54
Add a comment  | 

2 Answers 2

Reset to default 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 );

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();

本文标签: Find count of WordPress users by role and search string for user name