Site icon Hip-Hop Website Design and Development

Allow users with Editor role to edit menus (without a plugin)

I came across the need to have a site Editor to edit menus. I found some answers that suggest the add_cap() approach, to add the edit_theme_options capability to Editor role.

This should be done once and then removed from functions.php:

// Do this only once. Can go anywhere inside your functions.php file
$role_object = get_role( 'editor' );
$role_object->add_cap( 'edit_theme_options' );

The same answer shows a way to hide unwanted Appearance sub-menus. But it also hides those sub-menus to Administrator role.

My question is: is this a right way to solve that problem and show the sub-menus to Admin but hide them to Editor role?

// Show Appearance sub-menus only to users with 'manage_options' capability

function hide_menu() {
    if ( ! current_user_can( 'manage_options' ) ) {
        remove_submenu_page( 'themes.php', 'themes.php' ); // hide the theme selection submenu
        remove_submenu_page( 'themes.php', 'widgets.php' ); // hide the widgets submenu
        remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Ftools.php' ); // hide the customizer submenu
        remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Ftools.php&autofocus%5Bcontrol%5D=background_image' ); // hide the background submenu

        // these are theme-specific. Can have other names or simply not exist in your current theme.
        remove_submenu_page( 'themes.php', 'custom-header' );
        remove_submenu_page( 'themes.php', 'custom-background' );
    }
}

add_action('admin_head', 'hide_menu');