How to replicate a field data for all of the existing orders in Woocommerce

71 Views Asked by At

I have a field CIF in my Woocommerce, I have 1000 orders with this field complete. This field shows because I used a plugin. ID Field is billing_cifnif.

Now I need to change this plugin for other plugin and I need that old field to be duplicated in a new field ID billing_nif.

I need to fill these 1000 orders with the new value.

I have this code:

add_action('woocommerce_thankyou', 'replicate_billing_email', 100, 1);

function replicate_billing_email($order_id){
    $order = new WC_Order($order_id); 
    $billing_cifnif = $order->get_billing_cifnif(); 
    update_post_meta($order_id, 'billing_nif', $billing_cifnif);
    update_post_meta($order_id, '_billing_nif', $billing_cifnif);
}

It only works for new orders, I need to use it for the old orders.

Thank you

1

There are 1 best solutions below

0
Ruvee On

"Only works for new orders, I need to use it for the old orders."

If you want to update your existing orders, then run the following snippet ONCE. After it's done running, delete it from the functions.php file:

add_action('wp_head', 'updating_orders_metadata');

function updating_orders_metadata()
{
    $orders = wc_get_orders(array('numberposts' => -1));

    if ($orders) 
    {
        foreach ($orders as $order) 
        {
            $billing_cifnif = $order->get_billing_cifnif();

            if ($billing_cifnif) 
            {
                update_post_meta($order->get_id(), 'billing_nif', $billing_cifnif);
                update_post_meta($order->get_id(), '_billing_nif', $billing_cifnif);
            }
        }
        echo "<div style='background-color: lightgreen; font-size: 20px; text-align: center;'>Done updating the orders! You may now delete the script from the functions.php file</div>";
    }
};

NOTE:

  • In order for updates to happen you would need to refresh your website home page ONCE. After your website home page is done loading and you see the green notice, go back to the functions.php file and remove the script!

enter image description here

  • I was not sure if you needed both billing_nif and _billing_nif, so I included both! Please feel free to exclude/delete any of them as you see fit!