How to remove access to menu options in admin panel

How can I restrict access to menu or submenu items in WordPress admin dashboard according to the user’s role ?

This function allow to restrict access to an element by url (e. g. /wp-admin/upload.php) or depending on the url parameter (e. g. post_type=acf_option_page) which is very useful to remove access to custom post type.

Insert this code on your functions.php file or plugin:

<?php
/*
* Remove access to menu options in admin panel for editors
*
*/
add_action( 'admin_init', 'restrict_admin_with_redirect' );
function restrict_admin_with_redirect() {
	$restrictions = array(
		'/wp-admin/upload.php',
		'post_type=acf_option_page'
	);
	if( current_user_can('editor')) {
		foreach ( $restrictions as $restriction ) {
			if ($_SERVER['PHP_SELF'] == $restriction) {
				wp_redirect(admin_url());
				exit;
			}
			if ($_SERVER['QUERY_STRING'] == $restriction) {
				wp_redirect(admin_url());
				exit;
			}
		}
	}
}
?>

Please not that this function only remove the access, but the menu items will remain visible!

Submit a Comment

Your email address will not be published. Required fields are marked *