Skip to content

Mapping Guest Orders to New / Returning User Accounts

Posted in WooCommerce

This is a useful snippet that I put together for a client recently, and wanted to share. When a user creates a new account or logs in, the e-mail address for the account is checked against stored guest orders. If a match is found, the orders are remapped to the user account, and any file downloads are also remapped.


add_action( 'user_register', 'initial_match_past_orders', 10, 1 );

function initial_match_past_orders( $user_id ) {

	$current_user = get_user_by( 'ID', $user_id );
	$email = $current_user->user_email;

	$customer_orders = get_posts( array(
                    'meta_key'    => '_billing_email',
                    'meta_value'  => "$email",
                    'post_type'   => 'shop_order',
		    'post_status' => 'wc-completed',
                    'numberposts'=>-1
                ) );

	if (!empty($customer_orders)) {
		
		global $wpdb;
		$prefix = $wpdb->prefix;
		$table=$prefix.'woocommerce_downloadable_product_permissions';
		$data = array('user_id'=>"$user_id");
		$where = array('user_email'=>"$email",'user_id'=>'0');

		$wpdb->update( $table, $data, $where, $format = null, $where_format = null );
         

                foreach($customer_orders as $k => $v){

		    $order_id = $customer_orders[ $k ]->ID;
                    update_post_meta( $order_id, '_customer_user', $user_id, 0);			
                }
         }
}

add_action('wp_login', 'returning_match_past_orders', 10, 2);

function returning_match_past_orders($user_login, $current_user) {
    
	$user_id = $current_user->ID;

	$email = $current_user->user_email;
	

	$customer_orders = get_posts( array(
                    'meta_key'    => '_billing_email',
                    'meta_value'  => "$email",
                    'post_type'   => 'shop_order',
		    'post_status' => 'wc-completed',
                    'numberposts'=>-1
     ) );

	if (!empty($customer_orders)) {
		
		global $wpdb;
		$prefix = $wpdb->prefix;
		$table=$prefix.'woocommerce_downloadable_product_permissions';
		$data = array('user_id'=>"$user_id");
		$where = array('user_email'=>"$email",'user_id'=>'0');
		$wpdb->update( $table, $data, $where, $format = null, $where_format = null );
       

                foreach($customer_orders as $k => $v){

		   $order_id = $customer_orders[ $k ]->ID;
		   update_post_meta( $order_id, '_customer_user', $user_id, 0);
		   
		}
	}
	
}

Gist Link: Map Guest Orders Gist