How do I re-direct non admin and end users to home when hitting wp-admin (WordPress)

when an external user or non admin tries to access http://www.urlVisibleToUsers.com/wp-admin gets re-directed to an error page, but still the home_url (where the WP installation resides) is exposed and visible. I would like to be able to re-direct all the end users or any role that is not an admin to http://www.urlVisibleToUsers.com/ and preventing adjax calls from breaking. I have the below code in my functions.php, but still an external user will see the home_url address in the navigation bar (although an error page is displayed):

add_action( 'admin_init', 'admin_area_for_manage_options_only');
function admin_area_for_manage_options_only() {

      if( defined('DOING_AJAX') && DOING_AJAX ) {
            //Allow ajax calls in order to have ALM working
            return;
      }

      if( ! current_user_can( "manage_options" ) ) {
           //Redirect to main page if the user has no "manage_options" capability
           wp_redirect( get_site_url( ) );
           exit();
      }
 }

Not sure why the above code is not working, is that the correct approach? Should I have introduced Apache re-direct rules in my .htaccess, instead? Can you help?

Thank you for your help

Read more here: How do I re-direct non admin and end users to home when hitting wp-admin (WordPress)

Leave a Reply

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