I’m using WP_User_Query to bring back a list of users. According to this article, I can focus the query on particular columns (I’m assuming in the wp_users table) using the search_columns param.

My query:

$args = array(
    'search' => 'Rami',
    'search_columns' => array( 'user_login', 'user_email', 'display_name' ),
);
$user_query = new WP_User_Query( $args );

My aim is to have my query look in the display_name column but that doesn’t seem to be working. Interestingly, display_name isn’t a mentioned column in the article example but it is definitely a column in the wp_users table.

How can I search the display_name column when using WP_User_Query?

2 Answers
2

You can try this:

/**
 * Add support for the "display_name" search column in WP_User_Query
 * 
 * @see http://wordpress.stackexchange.com/a/166369/26350
 */
add_filter( 'user_search_columns', function( $search_columns ) {
    $search_columns[] = 'display_name';
    return $search_columns;
} );

where we use the user_search_columns filter to modify the available search columns.

So what fields can we use with this filter? Here’s the list of all the fields in the wp_users table:

x ID
x user_login
  user_pass
x user_nicename
x user_email
x user_url
  user_registered
  user_activation_key
  user_status
  display_name

where I’ve marked the default search columns with an x.

Leave a Reply

Your email address will not be published. Required fields are marked *