wordpresswoocommercehook-woocommerceorders

How to link WooCommerce guest orders to customer account after registration


Our scenario is:

The guest user enters the site and places one or more orders without the need to register. And after a while, he decides to register on the site.

Now how to link guest orders to customer account after registeration?

I use the following code, but this code only works for users who have already registered but did not log in at the time of purchase. Any advice?

//assign user in guest order
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );
function action_woocommerce_new_order( $order_id ) {
    $order = new WC_Order($order_id);
    $user = $order->get_user();
    
    if( !$user ){
        //guest order
        $userdata = get_user_by( 'email', $order->get_billing_email() );
        if(isset( $userdata->ID )){
            //registered
            update_post_meta($order_id, '_customer_user', $userdata->ID );
        }else{
            //Guest
        }
    }
}

Solution

  • You can use the woocommerce_created_customer action hook and the wc_update_new_customer_past_orders() function

    So you get:

    function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) {
        // Link past orders to this newly created customer
        wc_update_new_customer_past_orders( $customer_id );
    }
    add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 );