Search code examples
phpwordpresswoocommercepasswordsaccount

What is the equivalent of wp_set_password function in WooCommerce?


I found out that I can customize the wp_set_password function and put my code in it. But it's only executed when a user register through /wp-login.php.

This was my code:

function wp_set_password( $password, $user_id ) {
    // Keep original WP code
    global $wpdb;

    $hash = wp_hash_password( $password );
    $wpdb->update(
        $wpdb->users,
        array(
            'user_pass'           => $hash,
            'user_activation_key' => '',
        ),
        array( 'ID' => $user_id )
    );

    wp_cache_delete( $user_id, 'users' );

    // and now add your own
    $custom_hash = password_hash( $password, PASSWORD_DEFAULT );
    update_user_meta($user_id, 'user_pass2', $custom_hash);
}

However I have installed WooCommerce and all three main tasks regarding password are:

  • Registration,
  • Profile update,
  • Password reset.

So this code doesn't help me with that and I've searched for a similar function in WooCommerce, but I couldn't find it. Is there anyway that I can edit WooCommerce like this in my custom plugin and what is the function to do that?


Solution

  • You should always avoid to overwrite any core file, as you will loose your changes when WordPress will be updated and you can make big trouble in this related sensible processes.

    In Woocommerce the equivalent of WordPress wp_set_password() is the WC_Customer set_password() method.

    To get it pluggable you can use [WC_Customer_Data_Store][4] Class related hooks located in update() method:

    • On user creation, for "User registration", use woocommerce_new_customer action hook .
    • On user update events, use woocommerce_update_customer action hook
    • On "User registration" (user creation), you can use woocommerce_new_customer action hook
    • When changing/saving the password on My account > Account details section, you can use woocommerce_save_account_details action hook too.
    • When the password get reseted you can use woocommerce_customer_reset_passwor action hook.

    Example usage of WC_Customer set_password() method:

    // Get the WC_Customer instance object from the user ID
    $customer = new WC_Customer( $user_id );
    
    // Set password
    $customer->set_password( $password );
    
    // Save to database and sync
    $customer->save();