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 found the following code, but this code only works for users who have already registered but did not log in at the time of purchase.
//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
}
}
}