Archives

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