matin
matin

Reputation: 121

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
        }
    }
}

Upvotes: 4

Views: 2918

Answers (2)

7uc1f3r
7uc1f3r

Reputation: 29624

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 ); 

Upvotes: 7

Adam
Adam

Reputation: 34

Use the answer provided by @7uc1f3r, but if you want to link all orders previously created to existing users, use this function additionally.

Add the function to your functions php and let it run ONCE, then remove it again as letting it run on every page load is not required if you use the accepted answer

//loop through all users and link their orders
function my_link_all_users_orders()
{
    $users = get_users();
    foreach ($users as $user) {
        wc_update_new_customer_past_orders($user->ID)
    }
}
add_action('init', 'my_link_all_users_orders');

Upvotes: 0

Related Questions