Sort “My Sites” Menu Alphabetically

If you have a WordPress Network and you use the My Sites menu a lot, you might wish the list was sorted alphabetically, rather than by site ID.

Here’s how you can reorder that list

Method 1: Modify the Admin Bar/Toolbar directly

add_action('admin_bar_menu', 'reorder_my_sites');
function reorder_my_sites( $wp_admin_bar ) {

    //get "my sites"
    $mysites = $wp_admin_bar->user->{'blogs'};
    //and remove the unsorted list
    unset( $wp_admin_bar->user->{'blogs'} );

    //loop thru mysites to get id and title
    $pairs = array();
    foreach($mysites as $id => $info) {
        $pairs[$id] = strip_tags($info->blogname);
    }
    $pairs = array_map( 'strtoupper', $pairs );
    //sort by title, keep id
    asort($pairs);

    //loop thru sorted sites, and put back in menu
    foreach ($pairs as $id => $title) {
        $wp_admin_bar->user->{'blogs'}->$id = $mysites[$id];
    }
}

Method 2: Reorder the user’s blogs, before the menu is rendered

add_filter('get_blogs_of_user','reorder_users_sites');
function reorder_users_sites( $blogs ) {
	$f = create_function('$a,$b','return strcasecmp($a->blogname, $b->blogname);');
	uasort( $blogs, $f );
	return $blogs;
}

Method 2 credit

 

7 thoughts on “Sort “My Sites” Menu Alphabetically”

  1. How do I use the above code snippet? It sounds like its exactly what I need, but I’m not sure where to add the code snippet. And is it as simple as adding it to an existing file functions?

  2. Thanks for this. The list not sorting on name has been a bit annoying. If I had known it was such a quick and easy fix I would have done this weeks ago.

  3. Thanks for this great snippet. I plan on implementing this ASAP. Am probably going to make a quick functionality plugin for this as I’d like it on multiple networks and I think it should be independent of the theme.

    I am also looking to see if there is a way to handle the My Sites list better when it gets too long for the screen. Any ideas on that? I was thinking of implementing something like this: http://css-tricks.com/long-dropdowns-solution/ but I’m not sure how.

Leave a Reply

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

%d bloggers like this: