WordPress.org

Forums

Sort Oder of Dropdown (6 posts)

  1. rramey
    Member
    Posted 2 years ago #

    I've been researching this without any success. I have a dropdown on my site using the following:

    wp_dropdown_users(array('name' => 'member', 'exclude' => '1'));

    The dropdown works fine, but I need to be able to sort by last name. How can I accomplish this?

  2. Rebecca O'Brien
    Member
    Posted 2 years ago #

    From the documentation, it looks like you can't order by last night. You can sort by ID, nicename or display name. last_name is stored as a meta value, so you may either need to use a custom query or simply retrieve all users and sort via PHP - in both cases, creating your own dropdown.

  3. rramey
    Member
    Posted 2 years ago #

    I know that I can't do it, which is why I created my post. I need to know How to do it.

  4. bcworkz
    Member
    Posted 2 years ago #

    No need to get snarky, we are not mind readers, we don't know what others know unless they care to share it. Rebecca DID tell you how to do it, a custom query or php routine to sort by a value fragment.

    First you'll need to develop a regexp that reliably returns last names from the combined value. Then you can either include it in an ORDERBY mysql statement or use it to build a structured array using one of the array sort functions like asort, ksort, usort, uksort, etc.

    From those results, you can easily build your own dropdown.

  5. rramey
    Member
    Posted 2 years ago #

    I don't know how to do any of that, so if someone could post an example that would be helpful.

  6. Rebecca O'Brien
    Member
    Posted 2 years ago #

    Merry Christmas. =) Basic dropdown with a list of all user display names, sorted by last name.

    function userDropDownByLastName($echo = true) {
        $args	= array('who' => 'all_with_meta');
        $results	= new WP_User_Query($args);
        if(!$results) { return false; }
        $users	= array();
        foreach($results->results AS $user) {
    	$users[$user->last_name] = $user->data;
        }
        ksort($users);
    
        $return	= '';
        $return .= "<select>
    		    <option></option>";
        foreach($users AS $lastName => $value) {
    	$return .= "<option value='{$value->display_name}'>{$value->display_name}</option>";
        }
        $return .= "</select>";
        if($echo) {
    	echo($return);
        }
        return $return;
    }
    userDropDownByLastName();

Topic Closed

This topic has been closed to new replies.

About this Topic