Sorting WordPress Users list by Custom Field


The following code show how to get WordPress user’s list which role is ‘subscriber’ and first name and billing city of that user is not blank. we can sort the user list by the user custom field. I have used ‘WP_User_Query’ to get the user list and it allows us to add meta query as well. in the order by add the custom field name which you want to sort. in this example I have sorted the list by first name. Please note ‘meta_key’ parameter must exists in the query arguments otherwise your custom field sorting will not work.

    $user_args = array(             
        'number' => -1,
        'meta_key'   => 'first_name',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'     => 'first_name',
                'value'   => '',
                'compare' => '!=' // remove empty users which do not have first name
            ),
            array(
                'key'     => 'billing_city', // custom user field
                'value'   => '',
                'compare' => '!=' 
            ),
            array(
                'key'     => 'wp_user_level', 
                'value'   => '0', // Subscriber only
                'compare' => '='
            )
        ),
        'orderby' => array( 
            'meta_value' => 'ASC',
        ),
    );  

        // The Query
        $user_query = new WP_User_Query($user_args);
        echo '<div class="user_list">';
        echo '<h3>Users List</h3>';
        if (!empty($user_query->get_results())) {
            foreach ($user_query->get_results() as $user) {
                $first_name = get_user_meta($user->ID, 'first_name', true); //first name
                $last_name = get_user_meta($user->ID, 'last_name', true); //last name
                $city_name = get_user_meta($user->ID, 'billing_city', true); //last name
                echo '<li>'. $first_name .' '. $last_name . ' [ '. $city_name .' ]</li>';
            }
        }
        echo '</ul>';

Output of the above code:

Published by PHP Technology Tutorials

PHP Developer

Leave a comment