Created
December 3, 2021 16:00
-
-
Save panoslyrakis/5905f71f1b50755350f0c761f867533c to your computer and use it in GitHub Desktop.
[General] - Replace Woocommerce orders customer ids.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: [General] - Replace Woocommerce orders customer ids. | |
* Description: [General] - Replace Woocommerce orders customer ids. | |
* Author: Panos Lyrakis @ WPMUDEV | |
* Author URI: https://premium.wpmudev.org | |
* License: GPLv2 or later | |
*/ | |
if ( ! defined( 'ABSPATH' ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) { | |
return; | |
} | |
add_action( | |
'admin_footer', | |
function() { | |
if ( ! isset( $_GET['mapuserorders'] ) || ! function_exists( 'wc_get_order_types' ) ) { | |
return; | |
} | |
$base_date = strtotime( '2021-11-04 13:52:00' ); | |
$mapped_users = get_option( 'tmp_user_id_map' ); | |
if ( ! empty( $mapped_users ) ) { | |
foreach ( $mapped_users as $mapped_user ) { | |
$old_user_id = isset( $mapped_user['old_id'] ) && is_numeric( $mapped_user['old_id'] ) ? (int) $mapped_user['old_id'] : null; | |
$new_user_id = isset( $mapped_user['new_id'] ) && is_numeric( $mapped_user['new_id'] ) ? (int) $mapped_user['new_id'] : null; | |
if ( is_null( $old_user_id ) || is_null( $new_user_id ) ) { | |
error_log( 'Skipped old user : ' . $old_user_id . ' -- New: ' . $new_user_id, 3, WP_CONTENT_DIR . '/new-order-customer.log' ); | |
continue; | |
} | |
$user_orders = get_posts( | |
array( | |
'numberposts' => -1, | |
'meta_key' => '_customer_user', | |
'meta_value' => $old_user_id, | |
'post_type' => wc_get_order_types(), | |
'post_status' => array_keys( wc_get_order_statuses() ), | |
) | |
); | |
if ( ! empty( $user_orders ) ) { | |
foreach ( $user_orders as $order ) { | |
$order_date = get_post_timestamp( $order->ID ); | |
if ( $base_date >= $order_date ) { | |
update_post_meta( $order->ID, '_customer_user', $new_user_id ); | |
error_log( "Order {$order->ID} updated customer id from {$old_user_id} to {$new_user_id} \n\n\n", 3, WP_CONTENT_DIR . '/new-order-customer.log' ); | |
} else { | |
error_log( "Order {$order->ID} Skipped customer id from {$old_user_id} to {$new_user_id} as order was made after {$base_date} \n\n\n", 3, WP_CONTENT_DIR . '/new-order-customer.log' ); | |
} | |
} | |
} | |
} | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment