Custom plugin - add_submenu_page settings

I have a custom settings page for a plugin, calling it following way:

add_action( 'admin_menu', 'kbnt_prihlaska_nastaveni_add_admin_menu' );

function kbnt_prihlaska_nastaveni_add_admin_menu(  ) {
	add_submenu_page( 'prihlasky_na_konferenci', 'Nastavení', 'Nastavení', 'edit_posts', 'nastaveni', 'kbnt_prihlaska_nastaveni_options_page' );
}

If I'm logged in as Admin, everything works fine. If I'm logged for example as editor (with "edit_posts" rights) It looks ok, I can view it however, I can't save the values - It stops me with "Are you cheating right" message.

How to fix it? Thanks a lot.

  • Rupok

    Hi Karolina,

    Thanks for asking. You said that you can see the options page but you can't save values on that page with "Editor" role users, right? I think it's not being caused by how you are adding submenu page, rather probably your "Editor" role doesn't have enough capability to update those options. In your code, you checked that if user has "edit_posts" capability,. That means, users who have "edit_posts" capability, will be able to see that page. But that doesn't necessarity mean that Editor user will be able to update options on that page and I don't know what options are in that page. So I'm not sure why your Editor role users can't update those. If there is any option which only admins can update, then you should be using this line:
    add_submenu_page( 'prihlasky_na_konferenci', 'Nastavení', 'Nastavení', 'update_core', 'nastaveni', 'kbnt_prihlaska_nastaveni_options_page' );
    That will make sure that only Admins will be able to see that page.

    Now to get idea regarding which user role has which capability (unless you have modified user roles and capabilities), you can check this official codex page: https://codex.wordpress.org/Roles_and_Capabilities

    If that page has any option which only admins can update, then this is normal. While coding for showing those options in that page, you should check current user role and if current user role is not capable of updating that option, you should hide that. You can check the following guides for reference:
    https://codex.wordpress.org/Function_Reference/wp_get_current_user
    https://codex.wordpress.org/Function_Reference/current_user_can

    I believe these will help. Please let us know if you have any confusion or if you are stuck at any point. We will be glad to help further.

    Have a nice day. Cheers!
    Rupok