4

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

12

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.

2
  • Much better solution.
    – shanebp
    Commented Oct 24, 2014 at 13:28
  • I updated the Codex page.
    – birgire
    Commented Oct 24, 2014 at 14:28
3

According to the codex, display_name isn't supported.

You could use the pre_user_query filter.

function henry_display_name_find( $query ) {
    global $wpdb;

    /* you don't say where the name comes from - this assumes a $_POST field */
    $display_name = $_POST['display_name'];

    $use_like_syntax = false;

    if ( $use_like_syntax = true ) {
        $query->query_where .= $wpdb->prepare( " AND $wpdb->users.display_name LIKE %s", '%' . like_escape( $display_name ) . '%' );
    } else {
        $query->query_where .= $wpdb->prepare( " AND $wpdb->users.display_name = %s", $display_name );
    }
}
add_action( 'pre_user_query', 'henry_display_name_find' );

You'll probably want to add and remove the filter in a function.

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.