WordPress Quick Fix: Redirect certain user role to homepage on login

Today I will show you how you can redirect certain user role to homepage, or restrict certain user level from accessing the admin dashboard area in WordPress. Say you create a site where you have different user levels that can access certain part of your site (front end) using their login credentials. However you do not want them to get inside the Dashboard (even though the access is restricted). For that all you have to do is add the following snippet to your theme file’s functions.php

function wp_cp_redirect(){
if( is_admin() && !defined('DOING_AJAX') && ( current_user_can('subscriber') || current_user_can('contributor') ) ){
wp_redirect(home_url());
exit;
}
}
add_action('init','wp_cp_redirect');

What this does is redirects any user whose role is either ‘subscriber’ or ‘contributor’ back to the homepage every time they try to access the admin dashboard.

Also a bonus tip (I am feeling happy today ;) )

If you do not want to show the Admin Menu on top of the page once you login, you could use the following code to do so. Just paste it  into your theme’s function.php

 
add_filter( 'show_admin_bar', '__return_false' );

Utsav Singh Rathour is a WordPress Enthusiast and a blogger with over 10 years of experience and believes in building applications that not only tackles the problem but gives users a better interface. He is founder of Code Pixelz Media and blogs mainly at this place. Follow him at @rathour

Share

Leave a Reply

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