I've written the following code to take Stripe payment details from a Woocommerce subscription and update the related order with those details.
It's grabbing the details fine but the update_post_meta
code doesn't seem to fire and just leaves those fields blank in the post meta, what am I missing? The rest of the code works as intended.
$order_id = wc_get_order( '143025' );
$subscriptions = wcs_get_subscriptions_for_order($order_id, array( 'order_type' => 'any' ));
foreach( $subscriptions as $subscription_id => $subscription_obj ){
$current_subs_id = $subscription_obj->get_id(); // This is current subscription id
$stripe_cus = get_post_meta( $current_subs_id, '_stripe_customer_id' );
$stripe_cus = $stripe_cus[0];
$stripe_src = get_post_meta( $current_subs_id, '_stripe_source_id' );
$stripe_src = $stripe_src[0];
update_post_meta( $order_id, '_stripe_customer_id', $stripe_cus );
update_post_meta( $order_id, '_stripe_source_id', $stripe_src );
}
The two strings look like cus_Hjgys757
and src_1nHyyin75
for $stripe_cus
and $stripe_src
.
It seems that you make a confuncion between order object and order ID in your code. Also you could try using CRUD methods instead like:
$order_id = 143025;
$order = wc_get_order( $order_id ); // Order Object
$subscriptions = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) ); // Array of subscriptions Objects
foreach( $subscriptions as $subscription_id => $subscription ){
$stripe_cust_id = $subscription->get_meta( '_stripe_customer_id');
$stripe_src_id = $subscription->get_meta( '_stripe_source_id' );
$order->update_meta_data( '_stripe_customer_id', $stripe_cust_id );
$order->update_meta_data( '_stripe_source_id', $stripe_src_id );
$order->save();
}
Or the old way using WordPress get_post_meta()
and update_post_meta()
functions:
$order_id = 143025;
$order = wc_get_order( $order_id ); // Order Object
$subscriptions = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) ); // Array of subscriptions Objects
foreach( $subscriptions as $subscription_id => $subscription ){
$stripe_cust_id = get_post_meta( $subscription_id, '_stripe_customer_id', true );
$stripe_src_id = get_post_meta( $subscription_id, '_stripe_source_id', true );
update_post_meta( $order_id, '_stripe_customer_id', $stripe_cust_id );
update_post_meta( $order_id, '_stripe_source_id', $stripe_src_id );
}
Both should work.