0

Restrict WordPress Admin to Specific User Groups

Posted (Updated ) in PHP

Another quick set of utility functions. If you wish to restrict WordPress admin to only users with specifics sets of permissions (such as only those higher than subscriber) use the following two actions in your functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Remove admin bar for users without adequate permissions
 */
add_action('after_setup_theme', function() { 
	if ( !current_user_can('edit_posts') )
		add_filter('show_admin_bar', '__return_false');	
});
 
/**
 * Redirect users without adequate permissions back to home page
 */
add_action('admin_init', function(){
	if ( !current_user_can('edit_posts') )
	{
		// Only redirect if not an AJAX request
		if ( empty($_SERVER['PHP_SELF']) || basename($_SERVER['PHP_SELF']) != 'admin-ajax.php' )
		{
			wp_redirect( site_url() );
			exit;
		}
	}
});

You can use any permission you like from the Roles and Capabilities section of the documentation to make admin accessible to just the user groups of your choice. There’s even a handy table showing which roles are available to which default user levels.