One of the things about working with the WordPress menu API (that is add_menu_page, add_submenu_page, and the like) is that it doesn’t make it easy to reorder the submenu items.

WordPress Admin Menu: Add Submenu Page

Sure, for certain things such as taxonomies or things like that, you can just change the order in which they are registered. But let’s say that you have a WordPress admin menu and then a few submenu pages under that particular menu.

By default, WordPress creates the top-level menu, and then it immediately creates a submenu item under the top-level menu that links to the same page. In many cases, this may be ideal.

In some cases, though, you may want to change that.

WordPress Admin Menu

To give an example of when you may want to change something could be something like this:

  • You have a top-level menu that is meant to offer options after connecting with a third-party API,
  • The third-party API requires an API key (or some other authentication), so you need to provide settings for that first,
  • Why not make the first menu item the Settings and the second menu item the actual API Tools?

Of course, when the settings have no been set, it’s helpful to also display a message in the main API Tools menu that the user should need to click over to the Settings page to enter their settings.

But that’s beyond the scope of this post. For now, here’s a way to manage re-ordering the menu from the server-side. First the code, then the explanation.

Generally speaking, I’m using this in the context of a namespaced object, but for this post, I’m relegating it to a function that exists in a namespace.

WordPress Admin Menu: Custom Menu Order

A few things to note:

  • I’m using the custom_menu_order hook which is an ideal place to work on the menu items in WordPress,
  • I’m looking specifically for the acme-api-tools submenu in the $menuName key of the $submenu array variable,
  • I create an array, $newSubmenu, and then swap the items and assign the new submenu to the existing submenu identified by the key.

There are a few comments – perhaps even problems (or at least serious considerations) – with this approach.

Namely, the code expects to know precisely the key we’re looking to work with. In some cases, this is fine, but if you’re looking to modify a menu for which you don’t know the key (like acme-api-tools), then you’re going to need to alter this.

Next, this also assumes there are only two menu items to swap. It’s easy enough in the case above, but if there were more, then you’d likely need a function to deal with moving things around and returning the new array.

Enough to Get Started

That said, the above functionality should give enough information for at least how to get started doing this, if not more, and then how to manipulate the submenu array that’s visible