get users with special roles in wordpress plugin

I am developing a plugin for wordpress and I want to get list of users with role1 or role2 or role3 or role4. I use the code below to get users with role1 but I don’t know how should I change it to get users of more than 1 role.

$jobholders = get_users( 'orderby=nicename&role=jobholder' ); 

Related posts

Leave a Reply

1 comment

  1. I thought that using a MySQL wildcard would work because the query in the class WP_User_Query is built with LIKE, but it doesn’t: get_users(array('role' => 'job%')).

    The solution has to be with the action hook pre_user_query:

    /**
     * Filter the mysql query for get_users when searching for the role "job" to search for "%job%"
     */
    add_action( 'pre_user_query', 'so_25594548' );
    
    function so_25594548( $user_search ) 
    {
        $search_str = '%"job"%';
    
        # Quotes around $search_str so we don't need to escape the backslashes
        if( false === strpos( $user_search->query_where, "$search_str" ) )
            return;
    
        # Simplify the LIKE to do a loose search
        $user_search->query_where = str_replace( 
            "$search_str", 
            '%job%', 
            $user_search->query_where 
        );
    }
    

    It considers that we have two roles, jobseeker and jobholder, and to search for both we would use this call, with an inexistant role but with a string that both contain (no wildcards): get_users(array('role' => 'job');. This makes query_where to be like this:

    WHERE 1=1 AND ( (wp_usermeta.meta_key = 'wp_capabilities' AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%"job"%') )
    

    wp_capabilities is a serialized array, so it looks for a perfect match for job between wildcards.