Auto create an user account after WooCommerce checkout without Plugin

To automatically create a user account after WooCommerce checkout, you can use the woocommerce_thankyou hook. Here’s how you can do it:

Steps to Auto-Create a User After WooCommerce Checkout

  • Check if the user is a guest (not logged in).
  • Generate a random password.
  • Create a new WordPress user.
  • Associate the order with the newly created user.
  • Send login details to the user.

Code Snippet for functions.php

Add this code to your theme’s functions.php file or a custom plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function auto_create_user_after_checkout( $order_id ) {
if ( !$order_id ) return;
 
$order = wc_get_order( $order_id );
$email = $order->get_billing_email();
$first_name = $order->get_billing_first_name();
$last_name = $order->get_billing_last_name();
 
// Check if user already exists
if ( email_exists( $email ) ) return;
 
// Generate a random password
$password = wp_generate_password();
 
// Create a new user
$user_id = wp_create_user( $email, $password, $email );
 
if ( is_wp_error( $user_id ) ) return;
 
// Update user meta
wp_update_user( array(
'ID' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'customer' // Assign WooCommerce customer role
));
 
// Link order to the new user
$order->set_customer_id( $user_id );
$order->save();
 
// Send email notification to user
$subject = "Your New Account Details";
$message = "Hello $first_name,\n\n";
$message .= "An account has been created for you on " . get_bloginfo( 'name' ) . ".\n";
$message .= "Here are your login details:\n\n";
$message .= "Username: $email\n";
$message .= "Password: $password\n\n";
$message .= "Login here: " . wp_login_url() . "\n\n";
 
wp_mail( $email, $subject, $message );
 
}
add_action( 'woocommerce_thankyou', 'auto_create_user_after_checkout' );

How This Works

✔ Automatically creates a user account if they checkout as a guest.
✔ Links the WooCommerce order to the new user.
✔ Emails login details to the customer.
✔ Assigns the “customer” role to the new account.

Related Posts


How to Retrieve and Expose Gutenberg & Theme-Generated CSS in WordPress

If you want to extract the CSS generated by Gutenberg and your WordPress theme, you can do so using ...

“Maximum Available Quantity Has Been Added to Cart” Error in WooCommerce

Seeing the “Maximum available quantity has been added to cart” error in WooCommerce? Thi...

WordPress Redirect Issues Across Multiple Websites

Experiencing redirect loops or unwanted redirects on multiple WordPress sites? Here’s a guide to d...

Woocommerce single product page css broken

If your WooCommerce single product page’s CSS is broken, here are some steps to troubleshoot a...