Woocommerce 订阅:从订阅元更新订单元数据

时间:2021-03-11 09:15:16

标签: php wordpress woocommerce crud woocommerce-subscriptions

我编写了以下代码以从 Woocommerce 订阅中获取 Stripe 付款详细信息,并使用这些详细信息更新相关订单。

它很好地抓住了细节,但 update_post_meta 代码似乎没有触发,只是在 post meta 中将这些字段留空,我错过了什么?其余代码按预期工作。

$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 );

}

cus_Hjgys757src_1nHyyin75 的两个字符串看起来像 $stripe_cus$stripe_src

1 个答案:

答案 0 :(得分:1)

您似乎在代码中混淆了订单对象和订单 ID。您也可以尝试使用 CRUD 方法,例如:

$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();
}

或者使用 WordPress get_post_meta()update_post_meta() 函数的旧方法:

$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 );
}

两者都应该有效。