Search code examples
phpwordpressauthenticationwoocommerceintersection

How to disable admin login from front end?


I'm trying to disable admin login from front end of my wordPress site but my backend login also gets disable both login shows admin cannot login here

<?php

add_filter( 'authenticate', 'wp_admin_prevent_authentication', 30, 3 );
function wp_admin_prevent_authentication( $user, $username, $password ) {
  if ( $user instanceof WP_User && is_page( 'my-account' ) )  {
    if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
      return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
    };
  };
  return $user;
};

Solution

  • Not sure you can use is_page() inside authenticate but you can get page name using $_SERVER['REQUEST_URI']. check the below code.

    function wp_admin_prevent_authentication( $user, $username, $password ) {
        
        $url = explode( '/', rtrim( $_SERVER['REQUEST_URI'], '/') );
    
        // If in My account dashboard page
        if(  $user instanceof WP_User && end( $url ) == 'my-account' ){ 
            if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
                return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
            }
        }
    
        return $user;
    } 
    add_filter( 'authenticate', 'wp_admin_prevent_authentication', 30, 3 );
    

    Tested and works.

    enter image description here