Skip to content

Instantly share code, notes, and snippets.

@duplaja
Last active May 22, 2019 02:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save duplaja/17e9dcce40f35dc7eb31b4e290cee7ab to your computer and use it in GitHub Desktop.
Save duplaja/17e9dcce40f35dc7eb31b4e290cee7ab to your computer and use it in GitHub Desktop.
Convert Guest Orders to Logged In
<?php
//Runs on User Registration
add_action( 'user_register', 'wc_map_guest_initial_match_past_orders', 10, 1 );
function wc_map_guestinitial_match_past_orders( $user_id ) {
//Get current users's e-mail from ID
$current_user = get_user_by( 'ID', $user_id );
$email = $current_user->user_email;
//Pulls all orders made with the user e-mail as the billing e-mail
$customer_orders = get_posts( array(
'meta_key' => '_billing_email',
'meta_value' => "$email",
'post_type' => 'shop_order',
'post_status' => 'wc-completed',
'numberposts'=>-1
) );
//If matching orders are found..
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');
//Updates all downloads with the same e-mail but user_id=0 (guest) to the correct user ID
$wpdb->update( $table, $data, $where, $format = null, $where_format = null );
//Updates all WC Orders with the e-mail to map to the correct user ID
foreach($customer_orders as $k => $v){
$order_id = $customer_orders[ $k ]->ID;
update_post_meta( $order_id, '_customer_user', $user_id, 0);
}
}
}
//Runs on login (to catch those who accidently make an order while not logged in
add_action('wp_login', 'wc_map_guest_returning_match_past_orders', 10, 2);
function wc_map_guest_returning_match_past_orders($user_login, $current_user) {
//Gets current user ID and e-mail
$user_id = $current_user->ID;
$email = $current_user->user_email;
//Pulls all orders made with the user e-mail as the billing e-mail
$customer_orders = get_posts( array(
'meta_key' => '_billing_email',
'meta_value' => "$email",
'post_type' => 'shop_order',
'post_status' => 'wc-completed',
'numberposts'=>-1
) );
//If matching orders are found..
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');
//Updates all downloads with the same e-mail but user_id=0 (guest) to the correct user ID
$wpdb->update( $table, $data, $where, $format = null, $where_format = null );
//Updates all WC Orders with the e-mail to map to the correct user ID
foreach($customer_orders as $k => $v){
$order_id = $customer_orders[ $k ]->ID;
update_post_meta( $order_id, '_customer_user', $user_id, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment