If you’re running a membership site on WordPress the last thing you want are your users accessing the WP admin area. The below code checks to see if we’re in the admin area and the current user is not an admin, then it redirects them back to the homepage.
It also does a check to see if we’re running AJAX. I once had a situation where I was blocking anyone who wasn’t an admin from the admin area, however and unforeseen consequence was any AJAX run on the front-end of the site, if they were logged in, would be blocked because all AJAX in a WordPress theme is run through admin-ajax.php
, which is an admin area file.
function redirect_users_away_from_admin() {
if(is_admin() && !current_user_can('admin') && !wp_doing_ajax()) {
wp_redirect(home_url());
exit;
}
}
add_action('init', 'redirect_users_away_from_admin');
Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.