4

Is it possible to change the capability set for a menu page, previously added with add_menu_page()?

I have a third plugin installed, that set a menu page created with a 'manage_options' capability, and severals submenus with the same capability:

add_menu_page( $title, __( 'Menu Example','menu-example' ), 'manage_options', $page, null , $icon_url );

add_submenu_page( $parent, $title1, $title1, 'manage_options', $page1 , $function1 );
add_submenu_page( $parent, $title2, $title2, 'manage_options', $page2 , $function2 );
add_submenu_page( $parent, $title3, $title3, 'manage_options', $page3 , $function3 );
add_submenu_page( $parent, $title4, $title4, 'manage_options', $page4 , $function4 );

I would like in my plugin to change the capability for this parent menu and only 2 submenus, and set my-custom-capability for this. I need this because I have a custom rol with limit menu pages.

1
  • in the hook admin_menu, you can edit the menu in $GLOBALS["menu"]
    – mmm
    Commented Apr 4, 2017 at 20:07

1 Answer 1

1

It is possible, but only with add_menu_page().

/**
 * Change admin menu after add menu page
 */
function wp_nh0afl5p_admin_menu_change() {
    global $menu;

    $page_slug = 'page-slug';
    $position  = wp_nh0afl5p_search_menu_position( $page_slug );
    
    /** check position */
    if ( ! is_numeric( $position ) ) {
        return;
    }

    /** change capability */
    $menu[ $position ][1] = 'my-custom-capability';

    /** add action again */
    add_action( $menu[ $position ][5], 'page_callback' );
}

add_action( 'admin_menu', 'wp_nh0afl5p_admin_menu_change', 11 );

/**
 * search submenu position
 *
 * @param $page_slug
 *
 * @return int|null
 */
function wp_nh0afl5p_search_menu_position( $page_slug ) {
    global $menu;

    foreach ( $menu as $i => $item ) {
        if ( $page_slug == $item[2] ) {
            return $i;
        }
    }

    return null;
}

It is very important that you add the page callback function again with add_action(). Because it is only added in the add_menu_page() function if current_user_can( $capability ), however, this is not fulfilled when the function is called.

There is a helper function that finds the menu position based on page slug.


It is not possible with add_submenu_page(). It stops at the beginning if it does not have the capability and so it doesn't add the submenu, so modification is not possible.

In this case, you have to add the submenu again with the add_submenu_page() function with the modified capability.

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.