"you are not allowed to access this page" error when using add_submenu_page

Viewed 3700

I'm using the add_submenu_page function of wp to add a sub menu inside a parent men, but I'm getting this error when accessing that submenu:

Sorry, you are not allowed to access this page.

I'm logged in as admin, flushed permalinks and logged out then logged in but nothing is changing.

my code:

class SPSetup {

    public function reg_func() {
        add_action( 'admin_menu', array( $this, 'sp_menu', ) );
    }

    public function sp_menu() {
        add_submenu_page( 
            'montheme_options', 'SP Dashboard', 'SP Dashboard', 
            'manage_options', 'sp-control', 
            array( $this, 'callback' ) 
        );
    }      
}


if ( class_exists( 'SPSetup ' ) ) {
    $SP= new SPSetup ();
    $SP->reg_func();
} 
2 Answers

TLDR: Add a lower priority, such as 99, to the action that creates the submenu page.

add_action( 'admin_menu', 'wpdocs_register_my_custom_submenu_page', 99 );

In my case I was trying to add a submenu to a preinstalled plugin menu so I got the same error.

Thanks to isabel104 and her comment I solved it:

https://developer.wordpress.org/reference/functions/add_submenu_page/#div-comment-4596

Regarding the 1st note in the More Information section above, you may also run into the “Sorry, you are not allowed to access this page.” message even if you’ve hooked correctly into the admin_menu hook. This error message will happen if all of these are true:

Your parent page is a custom page that you added using add_menu_page, and That parent page was created in another plugin, not the same plugin that is creating the submenu page, and You didn’t add a lower priority to the admin_menu hook for the add_submenu_page call, so the submenu page may be fired before the parent page–causing an error.

Solution: Add a lower priority, such as 99, to the action that creates the submenu page. For example:

add_action( 'admin_menu', 'wpdocs_register_my_custom_submenu_page', 99 );
Related