I have two plugins – one is the “primary” plugin called “SmartPost” and I’m trying to extend it with another plugin called “SmartPost E-mails”. So, in other words, “SmartPost E-mails” extends and depends on “SmartPost” to exist and load before the e-mails plugin does.
Within the SmartPost plugin, I have the following admin menu creation functions:
class sp_admin{
add_action( 'admin_menu', array('sp_admin', 'sp_admin_add_template_page') );
add_action( 'admin_menu', array('sp_admin', 'sp_admin_add_category_page') );
function sp_admin_add_template_page() {
add_menu_page( SP_PLUGIN_NAME, SP_PLUGIN_NAME, 'edit_dashboard', 'smartpost', array('sp_admin', 'sp_template_page'), null, null );
}
function sp_admin_add_category_page(){
add_submenu_page( 'smartpost', 'Settings', 'Settings', 'edit_dashboard', 'sp-cat-page', array('sp_admin', 'sp_settings_page') );
}
}
In my “SmartPost E-mails” plugin, I want to add a submenu to the SmartPost plugin page, so I have the following code:
class SP_Email_Admin_Page{
function __construct(){
add_action( 'admin_menu', array($this, 'sp_add_email_admin_page') );
}
function sp_add_email_admin_page(){
if( ( is_plugin_active( "smartpost-templates/smartpost.php" ) ) && defined( "SP_PLUGIN_NAME" ) ){
add_submenu_page( 'smartpost', 'E-mail Settings', 'E-mail Settings', 'edit_dashboard', 'sp-email-settings', array($this, 'sp_render_email_admin_page') );
}
}
function sp_render_email_admin_page(){
?>
<p>Hello World</p>
<?php
}
}
$sp_admin_page = new SP_Email_Admin_Page();
This results in strange behavior as described in this post. The submenu is added, but is linked improperly (the ‘admin.php?’ prefix is missing). I think it has to do with the fact that the add_submenu_page is defined outside of the same scope as where the parent menu page was defined – but I’m not sure why that would be a factor. This begs two questions: 1) Why is this happening and 2) how do plugins such as WooCommerce allow 3rd party plugin developers to create sub-menus for the WooCommerce admin page when the add_submenu_page() is most likely defined outside of the same scope as the parent WooCommerce menu page ?
4 Answers
I renamed the “SmartPost E-mail” plugin folder so it loads after the “SmartPost” plugin – I think. I’m pretty sure this “weird” behavior has to do with the order in which plugins are loaded. If a plugin is loaded before its “parent” plugin, then the weird behavior mentioned above will probably happen.