PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] How to link WooCommerce guest orders to customer account after registration

 March 04, 2022     hook-woocommerce, orders, woocommerce, wordpress     No comments   

Issue

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


Answered By - 7uc1f3r
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing