add multipe sub menus using add_submenu_page
-
19-03-2021 - |
Question
I need to add multiple submeus under a single parent admin menu. i can add submenu using following syntax.
function register_my_sub_admin() {
add_submenu_page( '/pluginname/includes/admin-menu.php',
'title',
'menu_title',
'manage_options',
'/pluginname/includes/submenu.php',
'',
plugins_url( 'pluginname/images/icon.png' )
);
}
add_action( 'admin_menu', 'register_my_sub_admin' );
Since I have more than 10 submenus to register as above, i have to duplicate the above code as much as needed.
So thinking, whether can I use some foreach loop or someother array method to do one code block and register all submenu pages via one action hook / function.
Will something like below can make this happen ?
$sub_menu = array();
$sub_menu['page_title'] = array('page1','page2');
$sub_menu['menu_title'] = array('title1','title2');
$sub_menu['capability'] ='manage_options';
$sub_menu['slug'] = array('wp-admin.php','wp-login.php');
$sub_menu['function'] ='';
foreach ($sub_menu as $key => $value ){
add_submenu_page( '/pluginname/includes/admin-menu.php',
$key,$key,$key,$key,$key,
plugins_url( 'pluginname/images/icon.png' )
);
}
La solution
a loop is almost always a good solution to avoid to copy-paste code.
you just need to use a array of datas like that :
$submenus = [
[
"page_title" => "page1",
"menu_title" => "title1",
"slug" => "wp-admin.php",
],
[
"page_title" => "page2",
"menu_title" => "title2",
"slug" => "wp-login.php",
],
];
foreach ($submenus as $value) {
add_submenu_page(
'/pluginname/includes/admin-menu.php',
$value["page_title"],
$value["menu_title"],
'manage_options',
$value["slug"],
'',
plugins_url( 'pluginname/images/icon.png' )
);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange