0

website administrator can login using woocommerce my-account page. is there any way to prevent this and change the login page for admin? I mean the admin username, email and password will be acceptable only in my custom login page.

1 Answer 1

1

To achieve this we can prevent admins from being authenticated into the site even with correct login and password unless they are using the WordPress default form instead of the WooCommerce login page.

First, we need to distinguish between one form and the other when processing the login request, to do so we need to add a hidden field to WP's core login form:

/**
 * Add a hidden field to admin login page to distinguish where request originated
 */
function wpse_398884_add_admin_login_hidden_field() {
    echo '<input type="hidden" name="admin-login-page" value="1" />';
}
add_action( 'login_form', 'wpse_398884_add_admin_login_hidden_field', 10, 0 );

Then we hook to filter inside the wp_authenticate function. First we check if the user was correctly authenticated and then if admin-login-page variable is set. If it is not, that means login was made from WooCommerce form so we return an error with a message for the user.

/**
 * Restrict admin login access only to main WordPress login form
 */
function wpse_398884_restrict_admin_login_location( $user, $username, $password ) {

    if ( $user instanceof WP_User && ! isset( $_POST['admin-login-page'] ) ) {
        if ( array_intersect( (array) $user->roles, [ 'administrator' ] ) ) {
            return new WP_Error( 'admin-error', 'Use admin login page instead.' );
        }
    }

    return $user;
}
add_filter( 'authenticate', 'wpse_398884_restrict_admin_login_location', 40, 3 );
1
  • you are the best. Thank you so much.
    – Nina
    Dec 6, 2021 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.