Halloween Sale 15% off Ends in See the plans
PHP

Sort "My Sites" Alphabetically in the Admin Bar

Orders the sites in the toolbar's My Sites menu by name instead of by creation date, which makes long lists much easier to scan.

Don’t have WPIDE yet? Install it on your site

Code

if ( ! is_multisite() ) {
    return;
}

add_action( 'admin_bar_menu', function ( $bar ) {
    if ( empty( $bar->user->blogs ) || count( $bar->user->blogs ) < 3 ) {
        return;
    }

    $main  = get_main_site_id();
    $blogs = $bar->user->blogs;

    uasort( $blogs, function ( $a, $b ) use ( $main ) {
        if ( (int) $a->userblog_id === $main ) {
            return -1;
        }
        if ( (int) $b->userblog_id === $main ) {
            return 1;
        }
        return strcasecmp( $a->blogname, $b->blogname );
    } );

    $bar->user->blogs = $blogs;
}, 19 ); // My Sites is built at priority 20.

Notes

The main site stays first; change the comparison to sort by address instead.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.