Sort admin menu items

It can be done sorting the global $submenu.

The sorting that’s applied resets the key number of the sub-array $submenu['options-general.php'], which is:

array
  'options-general.php' => 
    array
      10 => 
        array
          0 => string 'General'
          1 => string 'manage_options'
          2 => string 'options-general.php'
      15 => 
        array
          0 => string 'Writing'
          1 => string 'manage_options'
          2 => string 'options-writing.php'
      // etc

and becomes:

array
  'options-general.php' => 
    array
      0 => 
        array
          0 => string 'Discussion'
          1 => string 'manage_options'
          2 => string 'options-discussion.php'
      1 => 
        array
          0 => string 'General'
          1 => string 'manage_options'
          2 => string 'options-general.php'
      // etc

Here, we are considering the length of the default items equal to six. Prior to WordPress 3.5, there were 7 items, Privacy is now gone and embedded with the Reading tab.

Testing locally, this doesn’t produce any unexpected result and works ok. Maybe if a plugin depended on $submenu['options-general.php'][15] to position itself or something else, bugs could happen.

Sort is being applied separately for the default items and for the rest of them. Just disable the usort of the first block and you have your desired output.

add_action( 'admin_menu', 'sort_settings_menu_wpse_2331', 999 );

function sort_settings_menu_wpse_2331() 
{
    global $submenu;

    // Sort default items
    $default = array_slice( $submenu['options-general.php'], 0, 6, true );
    usort( $default, 'sort_arra_asc_so_1597736' );

    // Sort rest of items
    $length = count( $submenu['options-general.php'] );
    $extra = array_slice( $submenu['options-general.php'], 6, $length, true );
    usort( $extra, 'sort_arra_asc_so_1597736' );

    // Apply
    $submenu['options-general.php'] = array_merge( $default, $extra );
}

//http://stackoverflow.com/a/1597788/1287812
function sort_arra_asc_so_1597736( $item1, $item2 )
{
    if ($item1[0] == $item2[0]) return 0;
    return ( $item1[0] > $item2[0] ) ? 1 : -1;
}

reordered menu items

Leave a Comment