how to prevent wordpress admin from logging in via woocommerce my-account page

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.

Topic wp-login-form account php security Wordpress

Category Web


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.