1

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' )
        );
    }

1 Answer 1

0

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' )
    );


}
2
  • Great, This is exactly what i was trying to achieve. one more thing, Is there a way to fold these items under the parent slug and expand on click of parent slug ?
    – Shirantha
    Apr 21, 2018 at 18:09
  • yes it's possible, create a new question for that.
    – mmm
    Apr 21, 2018 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.