This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Restricting Access to the WordPress Dashboard By User Role

I see this a lot with people using the WP User Manager plugin to turn their WordPress site into a community or membership site. Users register for the site from the front end form, they are given a certain role (eg. subscriber), they then can manage their own profile from the front end of the site, but then also have access to the WordPress dashboard (via /wp-admin).

This isn’t the best experience for users who shouldn’t be seeing any form of wp-admin (even if they can’t do much in it). Here’s how you can lock down the dashboard to only administrators:

/**
 * Only allow access to the wp-admin dashboard for users with the manage_options capability (administrators).
 * Customize the capability as needed https://wordpress.org/support/article/roles-and-capabilities/
 */
function wpum_restrict_wp_admin_access() {
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		// Don't hijack AJAX requests
		return;
	}

	if ( ! is_admin() ) {
		// We aren't in the admin
		return;
	}

	if ( current_user_can( 'manage_options' ) ) {
		// User has the correct role
		return;
	}

	// Redirect to the homepage. Customize as needed
	wp_safe_redirect( home_url() );
	exit;
}

add_action( 'init', 'wpum_restrict_wp_admin_access' );

The admin bar will still appear for users on the front end of the site, which WP User Manager has a setting to disable it, but you can do this manually with the following:

/**
 * Only show the wp-admin bar for users with the manage_options capability (administrators).
 * Customize the capability as needed https://wordpress.org/support/article/roles-and-capabilities/
 *
 * @param bool $show_admin_bar
 *
 * @return bool
 */
function wpum_hide_admin_bar( $show_admin_bar ) {
	if ( ! current_user_can( 'manage_options' ) ) {
		return false;
	}

	return $show_admin_bar;
}

add_filter( 'show_admin_bar', 'wpum_hide_admin_bar' );

About

Iain Poulson is a WordPress and PHP developer, writer, and plugin author. His plugins include Intagrate the WordPress publishing for Instagram, and WP User Manager the membership, user profile, and community plugin. He also co-hosts the WordPress development and business podcast Pressing Matters. You can find him on Twitter @polevaultweb.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.