2,472 Views

WordPress’s admin system is pretty solid, but sometimes you might want to tweak the admin menus in WordPress to better fit your workflow or your client’s needs. WordPress does let you add or remove menu items using built-in functions, but knowing how the menus work behind the scenes gives you even more flexibility. Let’s show you how to create a plugin that lets you reorder admin menu items however you want, while breaking down how the WordPress menu system actually works.

How WordPress Orders Menu Items

To understand how menu positioning can cause issues, let’s create a simple plugin that demonstrates how WordPress orders menu items when adding them. Start by creating a directory for your plugin:

  1. Navigate to your WordPress installation’s wp-content/plugins directory.
  2. Create a new folder named admin-menu-customizer.
  3. Inside this folder, create a file named admin-menu-customizer.php.

Add the following plugin header to admin-menu-customizer.php:

<?php
/*
Plugin Name: Admin Menu Customizer
Description: A plugin to customize admin menus in WordPress.
Version: 1.0
Author: Your Name
License: GPL2
*/

Adding a New Menu Item

WordPress recommends using the admin_menu action hook to add admin pages. Here’s how you can add a new menu item to the admin menus in WordPress:

add_action('admin_menu', 'amc_add_custom_menu');
function amc_add_custom_menu() {
    add_menu_page(
        'My Custom Menu',      // Page title
        'My Custom Menu',      // Menu title
        'manage_options',      // Capability
        'my-custom-menu',      // Menu slug
        'amc_display_page',    // Function to display page content
        '',                    // Icon URL (optional)
        1                      // Position
    );
}
function amc_display_page() {
    echo '<h1>Welcome to My Custom Menu Page</h1>';
}

In this snippet of code, you’re setting up a custom menu in WordPress, and each parameter defines a key part of how it behaves:

  • Page Title: 'My Custom Menu' — This is what shows up in the browser tab when the page is open.
  • Menu Title: 'My Custom Menu' — This is the label that appears in the WordPress admin sidebar.
  • Capability: 'manage_options' — Only users with the ability to manage site settings (like admins) will see this menu.
  • Menu Slug: 'my-custom-menu' — This is a unique identifier for your menu. It’s used to load the page and handle its settings.
  • Function: amc_display_page — This function will generate the content of the page when the menu item is clicked.
  • Position: 1 — This controls where the menu item will show up in the admin menu in WordPress.

Activate the plugin from your WordPress dashboard. You should see a new menu item called “My Custom Menu” at the top of the admin menu, just above the Dashboard.

Understanding Position Conflicts

Now, change the position from 1 to 2 in the add_menu_page() function:

add_menu_page(
    'My Custom Menu',
    'My Custom Menu',
    'manage_options',
    'my-custom-menu',
    'amc_display_page',
    '',
    2 // Changed position to 2
);

Refresh your dashboard. You’ll notice that the Dashboard menu item has been replaced by your custom menu. This happens because WordPress uses a global array called $menu to store menu items, where the array keys correspond to the menu positions. If two menu items share the same position, the last one added overwrites the previous one.

The $menu Array Structure

Here’s how the $menu array might look:

Array
(
    [2] => Array
        (
            [0] => 'Dashboard',
            [1] => 'read',
            [2] => 'index.php',
            // Additional parameters...
        ),
    [5] => Array
        (
            [0] => 'Posts',
            [1] => 'edit_posts',
            [2] => 'edit.php',
            // Additional parameters...
        ),
    // Other menu items...
)

Each entry represents a menu item, with the key being the position. When you add a menu item at position 2, it replaces the existing item at that position in the admin menus in WordPress.

Specifying a Custom Menu Order

Custom Admin Menus in WordPress for Better Site Control

To reorder the admin menus in WordPress without overwriting existing items, you can use two filters: custom_menu_order and menu_order.

Enable Custom Menu Ordering:

add_filter('custom_menu_order', 'amc_enable_custom_menu_order');
function amc_enable_custom_menu_order() {
    return true;
}

Define the Custom Menu Order:

add_filter('menu_order', 'amc_set_custom_menu_order');
function amc_set_custom_menu_order($menu_ord) {
    if (!$menu_ord) return true;
    return array(
        'index.php',           // Dashboard
        'separator1',          // Separator
        'my-custom-menu',      // Your Custom Menu
        'edit.php',            // Posts
        'upload.php',          // Media
        'link-manager.php',    // Links (deprecated)
        'edit.php?post_type=page', // Pages
        'edit-comments.php',   // Comments
        'separator2',          // Separator
        'themes.php',          // Appearance
        'plugins.php',         // Plugins
        'users.php',           // Users
        'tools.php',           // Tools
        'options-general.php', // Settings
        'separator-last',      // Last Separator
    );
}

In the amc_set_custom_menu_order function, you return an array of menu slugs in the desired order. WordPress will arrange the admin menus in WordPress based on this array.

Creating a Custom Menu Manager

To make the menu reordering dynamic, let’s create an interface in the admin panel:

Adding a Submenu Page

add_action('admin_menu', 'amc_add_admin_page');
function amc_add_admin_page() {
    $hook_suffix = add_menu_page(
        'Admin Menu Manager',
        'Admin Menu Manager',
        'manage_options',
        'admin-menu-manager',
        'amc_admin_page_display'
    );
    add_action("load-$hook_suffix", 'amc_process_admin_page');
}

This code creates a new top-level menu item called Admin Menu Manager in the WordPress dashboard. The menu is only visible to users who have the 'manage_options' capability (usually admins). The content of this new page will be handled by the amc_admin_page_display function, and additional processing can be done using the amc_process_admin_page function when the page loads.

Displaying the Menu Items

Next, you’ll need to create the amc_admin_page_display function that will display all the menu items, allowing you to reorder them in the admin menus in WordPress.

function amc_admin_page_display() {
    // Get the current menu order
    $current_menu_order = get_option('amc_custom_menu_order');
    if (!$current_menu_order) {
        global $menu;
        $current_menu_order = array_column($menu, 2);
    }
    echo '<div class="wrap"><h1>Admin Menu Manager</h1>';
    echo '<form method="post">';
    echo '<ul>';
    foreach ($current_menu_order as $index => $menu_slug) {
        echo '<li>';
        echo '<input type="hidden" name="menu_order[]" value="' . esc_attr($menu_slug) . '">';
        echo esc_html($menu_slug);
        echo ' <a href="?page=admin-menu-manager&move=up&index=' . $index . '">↑</a>';
        echo ' <a href="?page=admin-menu-manager&move=down&index=' . $index . '">↓</a>';
        echo '</li>';
    }
    echo '</ul>';
    submit_button('Save Menu Order');
    echo '</form></div>';
}

This function does a few things:

  1. It grabs the global $menu array, which stores all the admin menu items.
  2. It creates a simple HTML form that lists the menu titles.
  3. The list of menu items is shown in an unordered list <ul>, and each menu title is displayed as a list item <li>.
  4. There’s a “Save Changes” button to save changes to the admin menus in WordPress, although at this point, it’s not yet doing anything (we’ll need to add that functionality later).

Processing Form Submissions

function amc_process_admin_page() {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // Save the new menu order
        if (isset($_POST['menu_order']) && is_array($_POST['menu_order'])) {
            update_option('amc_custom_menu_order', $_POST['menu_order']);
        }
    }
    // Handle move up and down actions
    if (isset($_GET['move']) && isset($_GET['index'])) {
        $index = (int) $_GET['index'];
        $move = $_GET['move'];
        $menu_order = get_option('amc_custom_menu_order');
        if (!$menu_order) {
            global $menu;
            $menu_order = array_column($menu, 2);
        }
        if ($move == 'up' && $index > 0) {
            // Swap with previous item
            $temp = $menu_order[$index - 1];
            $menu_order[$index - 1] = $menu_order[$index];
            $menu_order[$index] = $temp;
        } elseif ($move == 'down' && $index < count($menu_order) - 1) {
            // Swap with next item
            $temp = $menu_order[$index + 1];
            $menu_order[$index + 1] = $menu_order[$index];
            $menu_order[$index] = $temp;
        }
        update_option('amc_custom_menu_order', $menu_order);
        // Redirect to avoid resubmission
        wp_redirect(admin_url('admin.php?page=admin-menu-manager'));
        exit;
    }
}

This function handles the logic for moving menu items up or down and saving the new order.

Applying the Custom Menu Order

Modify the amc_set_custom_menu_order function to use the saved menu order:

function amc_set_custom_menu_order($menu_ord) {
    $custom_order = get_option('amc_custom_menu_order');
    if ($custom_order && is_array($custom_order)) {
        return $custom_order;
    }
    return $menu_ord;
}

This ensures that your customized admin menus in WordPress persist across sessions and are available to all users with the appropriate capabilities.

Storing and Retrieving Menu Structure

Custom Admin Menus in WordPress for Better Site Control

We use get_option() and update_option() to store and retrieve the custom menu order from the WordPress database. This ensures that your customized admin menus in WordPress persist across sessions and are available to all users with the appropriate capabilities.

Handling Additional Menu Items

Some plugins might add their own menu items at arbitrary positions. To include these in your custom menu manager, ensure that your code accounts for any new items:

function amc_admin_page_display() {
    global $menu;
    $all_menu_slugs = array_column($menu, 2);
    // Merge saved menu order with any new menu items
    $saved_menu_order = get_option('amc_custom_menu_order', array());
    $current_menu_order = array_unique(array_merge($saved_menu_order, $all_menu_slugs));
    // Rest of the display code...
}

This way, any new menu items added by plugins will appear in your menu manager, allowing you to reorder them within the admin menus in WordPress as needed.

Implementing Redirection for Immediate Updates

Custom Admin Menus in WordPress for Better Site Control

After processing menu changes, we use wp_redirect() to reload the page:

wp_redirect(admin_url('admin.php?page=admin-menu-manager'));
exit;

This ensures that the admin menus in WordPress are updated immediately, reflecting your changes without manual refreshes.

Summary

Customizing admin menus in WordPress enhances the dashboard experience, improving workflow and user satisfaction. WordPress hooks and filters like admin_menu, custom_menu_order, and menu_order enable effective reordering and management of menu items. Creating a plugin to implement these changes ensures they are organized and persist across sessions. This method aligns the WordPress admin interface with specific requirements, enhancing the overall efficiency of site management.