skip to Main Content

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;
};

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can try with the below code, maybe it will work for you.

    function wpum_admin_prevent_authentication( $user, $username, $password ) {
    
        if ( $user instanceof WP_User && is_page( wpum_get_core_page_id( 'login' ) ) ) {
            if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
                return new WP_Error( 'admin-error', 'Admins cannot login from here.' );
            }
        }
    
        return $user;
    
    }
    add_filter( 'authenticate', 'wpum_admin_prevent_authentication', 30, 3 ); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search