0

How to restrict access to /wp-admin based on user capabilities
By default WordPress allows access to the /wp-admin/ side if your site to all of the registered users. Of course the screens and data they may access is limited by their role: subscribers can only update their accounts and read announcements showing on in the dashboars, while contributors can write articles and moderate comments.

However, most of the time, either as a security measure or to force users update their profiles from the profile screen on the front-end we would rather restrict access to /wp-admin/ for some user roles.
This can be done by attaching a callback hook to the init action of WordPress, as shown below:

if (!function_exists('restrict_wp_admin')):
/**
* Restricts access to /wp-admin/ for users with roles below contributor.
* @author Adrian7 (http://wpdev.me/)
*/
function restrict_wp_admin () {

//check if the current user can edit_posts
//for available roles/capabilities to check against see http://codex.wordpress.org/Roles_an...
if( current_user_can('edit_posts') ) {
return true;
}

//redirects un-welcomed users to home page;
wp_redirect( home_url() ); exit;
}
endif;

if ( is_admin() ) add_action('init', 'restrict_wp_admin');

The code works as follows:

Checks if the current page is an wp-admin screen: if ( is_admin() ) ...;
If true (yes), attaches the callback function to the init action: add_action('init', 'restrict_wp_admin');
When the function is getting called during the init, it first checks if the current user can edit_posts: if( current_user_can('edit_posts') );
It he/she can, then it means it’s their role allows them to edit content https://domywriting.com/ , so it’s safe to let them continue: return true;
If they can’t, we’re gonna redirect them to the home page: wp_redirect( home_url() ); exit;;

The exit at the end is not actually required for the function to work, but it gives assurance in case wp_redirect fails for any reason, the request is not gonna go any further.

Comments
Your Job Suck?
Get a Better Job
Add Comment