<?php add_action('admin_menu', function() { add_menu_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', function() { echo '<h1>Welcome to My Plugin</h1>'; }, 'dashicons-admin-generic', 6); });
The add_menu_page function creates a new top-level menu. The callback echoes the heading, so it displays on the page. The icon 'dashicons-admin-generic' is a gear icon. Position 6 places it near the top.
Option B is missing a semicolon inside the anonymous function after echo 'Hi', causing a syntax error.
<?php add_action('admin_menu', function() { add_menu_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', 'my_plugin_page'); add_submenu_page('my-plugin', 'Sub Page', 'Sub Page', 'manage_options', 'my-plugin-sub', 'my_plugin_sub_page'); }); // After this runs, what is $submenu['my-plugin']?
When you add a top-level menu with add_menu_page, WordPress automatically adds a submenu item for it. Then add_submenu_page adds another submenu. So $submenu['my-plugin'] has two entries.
<?php add_action('admin_menu', function() { add_menu_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', 'my_plugin_page'); add_submenu_page('wrong-slug', 'Sub Page', 'Sub Page', 'manage_options', 'my-plugin-sub', 'my_plugin_sub_page'); });
The first parameter of add_submenu_page must match the parent menu slug exactly. Using 'wrong-slug' means WordPress cannot attach the submenu under 'my-plugin'.
The 'admin_menu' action runs early to build the menu structure. The callback functions for menu pages run later, only when the user visits that page. Submenus can be added after the top-level menu. 'admin_init' is not used for menu registration.