Home » WooCommerce: Automatically Register Guest Checkouts

WooCommerce: Automatically Register Guest Checkouts

by Tutor Aspire

A disclaimer first: please make sure this is legal in your country and also that your checkout visitors are aware they will become registered customers without explicit consent (i.e. without ticking a “create an account on this site” checkbox).

So, yeah, there is a way to turn guest checkouts into registered customer ones. Also, there is a neat WooCommerce function to bulk add all past guest orders to a new customer (wc_update_new_customer_past_orders).

Of course, “Allow customers to place orders without an account” must be enabled in your WooCommerce settings, otherwise you’re not allowing guest checkouts and the snippet will be irrelevant.

So, here’s the fix. Enjoy!

This screenshot requires a bit of context. With the snippet below, you automatically register guest users and sync their past guest orders as well. This means, if you wish, that you can totally disable the “Allow customers to create an account during checkout” WooCommerce setting because no matter what, user will be registered automatically. Hope that makes sense!

PHP Snippet: Automatically Register Guest Customers @ WooCommerce Checkout (and Programmatically Log Them In @ WooCommerce Thank You Page)

/**
 * @snippet       Register Guest Users @ WooCommerce Checkout
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 6
 * @donate $9     https://tutoraspire.com
 */

add_action( 'woocommerce_thankyou', 'tutoraspire_register_guests', 9999 );

function tutoraspire_register_guests( $order_id ) {
$order = wc_get_order( $order_id );
$email = $order->get_billing_email();
if ( ! email_exists( $email ) && ! username_exists( $email ) ) {
$customer_id = wc_create_new_customer( $email, '', '', array(
'first_name' => $order->get_billing_first_name(),
'last_name'  => $order->get_billing_last_name(),
));
if ( is_wp_error( $customer_id ) ) {
throw new Exception( $customer_id->get_error_message() );
}
wc_update_new_customer_past_orders( $customer_id );
wc_set_customer_auth_cookie( $customer_id );
} else {
$user = get_user_by( 'email', $email );
wc_update_new_customer_past_orders( $user->ID );
wc_set_customer_auth_cookie( $user->ID );
}
}

You may also like