How to Restrict WordPress Dashboard Access to Admins Only?

One of our clients asked how we would restrict access to the WordPress/Dashboard admin area to all other users except admins? Sometimes there are users on the site that are just regular users but not admin users. How to do that? To do this, add the code below to functions.php and all users who are not administrators and try to access the admin panel will be redirected to the homepage URL. This essentially provides a good way of keeping members away from anything WordPress on your site.

function restrict_admin_access(){
	global $current_user;
	get_currentuserinfo();
	if (!array_key_exists('administrator', $current_user->caps)) {
		wp_redirect( get_bloginfo('url') );
		exit;
	}
}
add_action('admin_init', 'restrict_admin_access', 1);

Basically, the way the code works is that, on line 2 within the function, we fetch the current user who is logged in. Once we have that in the variable, we check the session information for the current user on line 3. Every user information has attributes or properties. The properties contain the various permissions that the user has. In this case, we check to make sure the value administrator exists in the list of properties, if it doesn't we just redirect the user to the blog's homepage. This way the user is never able to access the dashboard or admin page.

Dotlayer is a knowledge-sharing platform built around a community of knowledge-seekers. We aim to make Dotlayer our readers' go-to source for all things tech-related. If you are interested in advertising or sponsorship opportunities, we are happy to discuss. Please submit all inquiries [email protected]. And if you enjoyed this post, we recommend reading our latest featured stories.

How to Restrict WordPress Dashboard Access to Admins Only?
Rate this post

Join over 20,000 users and get our best content

Each week we send 1 email to 20,000 smart entrepreneurs just like you. Enter your email below to join the crew.

Thank you for subscribing.

Something went wrong.

Leave a Comment