0
votes

I created a plugin and was writing the code for the page on the admin menu. The link in the backend menu appeared and was working fine (the link on the left hand toolbar). However, when I tried to click on it, the url loaded but I got the message on the page 'Sorry, you are not allowed to access this page.'

My initial code was below:

add_action('admin_init', 'settings_menu_page');

function settings_menu_page() {

    add_menu_page( 
    __('Settings Page', 'wpplugin'),
    __('Custom Settings', 'wpplugin'),
    'manage_options',
    'wpplugin',
    'settings_page_callback',
    '',
    85
 );

}

function settings_page_callback() {
    esc_html_e( 'Settings page text', 'wpplugin' );
}

And then I decided to change the action hook to 'admin_menu' so the code looked like:

add_action('admin_menu', 'settings_menu_page');

function settings_menu_page() {

    add_menu_page( 
    __('Settings Page', 'wpplugin'),
    __('Custom Settings', 'wpplugin'),
    'manage_options',
    'wpplugin',
    'settings_page_callback',
    '',
    85
 );

}

function settings_page_callback() {
    esc_html_e( 'Settings page text', 'wpplugin' );
}

And with this code I can see the page. The only thing that changed was the hook.

I've referenced the docs for admin_menu and admin_init and I'm at a bit of a loss as to what the difference between them is that is causing them to allow one with permissions but not the other.

Note: I was the same WordPress user for both of these with Administrator rights.

Does anyone know what the difference is here?

1

1 Answers

0
votes

The difference between the two hooks are when they are triggered. The admin_menu is triggered when a basic menu structure is in place and a basic admin panel has been initialized.

The hook admin_init on the other hand is triggered before any other admin side hooks that are triggered when the user accesses the admin area. Moreover, the admin_init hook does not run on user facing admin screens. It runs on admin-ajax.php and admin-post.php

You can read up more about these hooks and run sequence on the links mentioned below:

admin_init

admin_menu

Default actions Run on front and admin

Good Luck!!!