phpwordpresswoocommercehook-woocommercereset-password

WooCommerce Reset Password only by email


It is possible to change form-lost-password in the way, that user can be reset password only by email (validate username like email and show error, when input not email), I don't find a hook for this.


Solution

  • You can use "lostpassword_errors" hook.

    Please check line 2930 of wp-includes/user.php

    $errors = apply_filters( 'lostpassword_errors', $errors, $user_data );
    

    So, if you want to reset password only by email address, not by username, you can use following code.

    add_filter( 'lostpassword_errors', 'reset_password_by_email_only', 20, 2 );
    
    function reset_password_by_email_only( $errors, $user_data ) {
        $user_login = !empty($_POST['user_login'])?$_POST['user_login']:'';
    
        if ( empty( $user_login ) ) {
            $errors->add( 'empty_username', __( '<strong>Error</strong>: Please enter a username or email address.' ) );
        } elseif ( strpos( $user_login, '@' ) ) {
            $user_data = get_user_by( 'email', trim( wp_unslash( $user_login ) ) );
            if ( empty( $user_data ) ) {
                $errors->add( 'invalid_email', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
            }
        } else {
            $errors->add( 'invalid_input', __('<strong>Error</strong>: YOUR MESSAGE FOR INVALID INPUT HERE.' ) );
        }
    
        return $errors;
    }
    

    It will return error when user input is not email address.

    Hope it would help you.

    UPDATE:

    If you are using woocommerce and you want to reset password by email address only on myaccount page(customer area), you need to use "lostpassword_post" hook.

        add_action( 'lostpassword_post', 'reset_password_by_email_only', 20, 2 );
    
    function reset_password_by_email_only( $errors, $user_data ) {
        $user_login = !empty($_POST['user_login'])?$_POST['user_login']:'';
    
        if ( empty( $user_login ) ) {
            $errors->add( 'empty_username', __( '<strong>Error</strong>: Please enter a username or email address.' ) );
        } elseif ( strpos( $user_login, '@' ) ) {
            $user_data = get_user_by( 'email', trim( wp_unslash( $user_login ) ) );
            if ( empty( $user_data ) ) {
                $errors->add( 'invalid_email', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
            }
        } else {
            $errors->add( 'invalid_input', __('<strong>Error</strong>: YOUR MESSAGE FOR INVALID INPUT HERE.' ) );
        }
    }