4

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

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

4
  • Did you put the filter function into your functions.php file? Commented Jun 25, 2015 at 14:59
  • Yes this is the place Commented Jun 25, 2015 at 15:00
  • Could you update you original question with your new code? Commented Jun 25, 2015 at 15:01
  • I've updated it.. what about the parameters "$search" and "$this" ? can I ignore them? Commented Jun 25, 2015 at 15:10

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.