I’m trying to build a query with WP User Query where it’s possible to search after

  • user_email
  • user_nicename
  • first_name
  • last_name

This are my args:

$args = array(
            'role'              => 'author',
            'number'            => $limit,
            'offset'            => $offset,
            'order'             => $order_sort,
            'orderby'           => $order_by,
            'search'            => '*'.esc_attr( $search_str ).'*',
            'meta_query'        => array(
                'relation'      => 'AND',
                array(
                    'key'       => 'reg_complete',
                    'value'     => 1,
                    'compare'   => '=',
                ),
                array(
                    'relation'    => 'OR',
                    array(
                        'key'     => 'first_name',
                        'value'   => $search_str,
                        'compare' => 'LIKE'
                    ),
                    array(
                        'key'     => 'last_name',
                        'value'   => $search_str,
                        'compare' => 'LIKE'
                    )
                ),
            )
        );

working fine if searching after first / last name… but didnt match nicenames / email

any idea how to fix that?

edit:
removed the search_columns from args and added this filter:

add_filter( 'user_search_columns', 'my_user_search_columns', 10, 3 );

function my_user_search_columns( $search_columns, $search, $this ) {
    $search_columns[] = 'user_email';
    $search_columns[] = 'user_nicename';

    return $search_columns;
}

Same results as before the changes

1 Answer
1

You need to use the user_search_columns filter to add the columns you want to search on.

The user_search_columns filter is used to determine which user fields
in the database are used when performing a search on user information.

https://codex.wordpress.org/Plugin_API/Filter_Reference/user_search_columns

Leave a Reply

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