How can visitors redirect wp-admin to the homepage?

The codex entry for the admin_init hook has an example showing you how to do this.

 * Restrict access to the administration screens.
 * Only administrators will be allowed to access the admin screens,
 * all other users will be automatically redirected to
 * '' instead.
 * We do allow access for Ajax requests though, since these may be
 * initiated from the front end of the site by non-admin users.
function restrict_admin_with_redirect() {

    if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
        wp_safe_redirect( '' ); // Replace this with the URL to redirect to.

add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );

A few notes on how this works:

  • current_user_can( 'manage_options' ) checks to see if the logged in user has a capability only admin accounts should have. The proceeding ! means “not”. We are checking for a capability instead of simply checking for the admin role as a best practice. You should treat the role as nothing more than a label and check for capabilities (read: permissions) to check if a user can do something. Read more about the roles & caps here.
  • wp_doing_ajax() Makes sure the current request is not a WordPress Ajax request. If it is, it’s possible the user is not actually on the admin so no need to redirect. The proceeding ! means “not”.
  • wp_safe_redirect( '' ); Redirects the user to the URL you pass it. You can find the documentation here. Note: wp_safe_redirect() is the recommended function not wp_redirect(). Thanks @Nathan Johnson
    • exit; Stops execution of the script making the redirect the last action we do.
  • add_action( 'admin_init', 'restrict_admin_with_redirect', 1 ); Fire this check on the admin_init because it’s the first hook fired after authentication. Pass 1 as the last argument to make sure out function is fired before any other hooks.