I have a user meta field ('pkg_code') I would like to copy to a custom field ('log') on the users' order(s) upon update of their user profile.
I have looked through many similar posts on stackoverflow and elsewhere, trying a number of things. Most posts run this update of this kind when an order is placed, which would be fine going forward, but I need to append the user meta to previous orders right now, so the flow has to be on user profile update.
It seems maybe I have to have more than one action or an action and a filter to achieve the post meta update when user meta update occurs. But the hooks evade me. Greatly appreciate any and all thoughts.
add_action ( 'profile_update', 'sync_pkg', 11, 2 );
function sync_pkg( $user_id ) {
// On profile update GET pkg_code value save to variable $pkg
$pkg = get_user_meta( $user_id, 'pkg_code', true );
// with pkg value set, fetch orders belonging to the customer, and update the order with the pkg code value
$args = array(
'customer_id' => $user_id
);
$orders = wc_get_orders($args);
foreach ( $orders as $order ) {
$order_id = $order->get_id();
update_post_meta($order_id, 'log', $pkg ); // add and save the custom field
$order->save();
}
}
Update I have changed $orders for $order, but that still does not product a change in the custom field in the order.
When I try
update_post_meta($order_id, 'log', 'this is a test' );
That also doesn't update the custom field, so it seems there is something wrong in the posts query or I need another hook here.
I also tried replacing
$args = array(
'customer_id' => $user_id
);
$orders = wc_get_orders($args);
with
$orders = wc_get_orders( array(
'type' => 'shop_order', //important
'numberposts' => 1,
'orderby' => 'date',
'order' => 'DESC',
'meta_key' => '_customer_user',
'meta_value' => $user_id
) );
and no dice.