How To Add Sub Menu In WordPress Admin Panel

To add a sub-menu in the WordPress admin panel, you can use the `add_submenu_page()` function. Here’s a step-by-step guide on how to add a sub-menu in the WordPress admin panel:

1. Open the theme’s functions.php file in your WordPress theme directory (or create a new plugin file if you prefer).
2. Add the following code to the file:

 

// Add a top-level menu page
function custom_menu_page() {
    add_menu_page(
        'Custom Menu',    // Page title
        'Custom Menu',    // Menu title
        'manage_options', // Required capability to access the menu page
        'custom-menu',    // Menu slug
        'custom_menu_callback', // Callback function to render the menu page
        'dashicons-admin-generic', // Menu icon (optional)
        25   // Menu position (optional)
    );
}
add_action('admin_menu', 'custom_menu_page');

// Add a sub-menu page
function custom_submenu_page() {
    add_submenu_page(
        'custom-menu',    // Parent menu slug
        'Submenu',        // Page title
        'Submenu',        // Menu title
        'manage_options', // Required capability to access the menu page
        'custom-submenu', // Menu slug
        'custom_submenu_callback' // Callback function to render the submenu page
    );
}
add_action('admin_menu', 'custom_submenu_page');

// Callback function to render the menu page
function custom_menu_callback() {
    // Your menu page content goes here
    echo '<div class="wrap">';
    echo '<h1>Custom Menu</h1>';
    echo '<p>Welcome to the custom menu page!</p>';
    echo '</div>';
}

// Callback function to render the submenu page
function custom_submenu_callback() {
    // Your submenu page content goes here
    echo '<div class="wrap">';
    echo '<h1>Submenu</h1>';
    echo '<p>Welcome to the submenu page!</p>';
    echo '</div>';
}

 

3. Save the changes and upload the modified functions.php file (or the plugin file) back to your server.

This code adds a top-level menu page with the title “Custom Menu” and a sub-menu page with the title “Submenu” in the WordPress admin panel. The `add_submenu_page()` function accepts several parameters, including the parent menu slug, page title, menu title, required capability, menu slug, and callback function to render the submenu page.

The `custom_menu_callback()` and `custom_submenu_callback()` functions are the callback functions that render the content of the respective menu and submenu pages. You can modify these functions and add your own HTML and PHP code to customize the content.

After making these changes, you should see a new menu item labeled “Custom Menu” in the WordPress admin panel. When you hover over it, you’ll see the sub-menu item labeled “Submenu.” Clicking on the sub-menu item will display the content defined in the `custom_submenu_callback()` function.

Share This On :

Leave a Comment

Your email address will not be published. Required fields are marked *