Problem – First submenu item same as main menu in WordPress

While implementing a custom plugin in wordpress, we can simply add submenu items for our plugin by this code:

public function PluginMenu()
	{
		$this->my_plugin_screen_name = add_menu_page(
				'My Reviews',
				'My Reviews',
				'manage_options',
				__FILE__,
				array($this, 'RenderPage'),
				'dashicons-format-quote'
				);
	}

But in wordpress, if we add any submenu items to the plugin menu then it automatically generates another submenu item which is exactly same as main menu i.e same named menu that also redirects to same page as main menu.
Example:

In this situation, if we will try to delete this submenu item then it will delete the main menu also. To avoid this problem we have one solution i.e to rename the submenu item. Though it will still be redirected to the main menu page but it will look better than having same named menu items twice. To do so, we will just have to add a new line to our code for adding this menu. Now the code will become:

public function PluginMenu()
{
		$this->my_plugin_screen_name = add_menu_page(
				'My Reviews',
				'My Reviews',
				'manage_options',
				__FILE__,
				array($this, 'RenderPage'),
				'dashicons-format-quote'
				);
		add_submenu_page(__FILE__, 'Settings', 'Settings',   'manage_options',__FILE__, array($this, 'RenderPage') );
	}

And hence we will get our first submenu under the plugin’s main menu with a different name:

Leave a Reply

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