如何在 Woocommerce 订阅中将订单项元从父项复制到子订单项?

时间:2021-01-29 16:24:55

标签: wordpress woocommerce woocommerce-subscriptions

我正在运行一个与 woocommerce_order_status_completed 挂钩的函数,该函数使用 API 从外部来源获取电话号码和 pin,并将其保存在某些订单商品的元键中。其中一些订单项目是订阅。

使用当前代码,当 Woocommerce 订阅续订订单自动运行时,它会触发 API 并获取一组新的调用数据,但我想阻止它这样做。

我需要检查已完成的订单是否是订阅续订,如果是,则跳过 API 调用,而是获取续订商品的父元数据并将其插入到该子商品元数据中。

我在这里尝试的代码的顶部不起作用。 else{} 中代码的 API 调用部分正在运行,因此我已将其截断。

   add_action ( 'woocommerce_order_status_completed', 'add_item_meta_or_run_api', 10 , 1);

   function add_item_meta_or_run_api( $order_id ) {

      $order = wc_get_order( $order_id );

     // if (wcs_order_contains_subscription( $order, 'renewal' )){ //check if the order contains a renewal subscription
      
       if (wcs_order_contains_renewal( $order_id)){ //Updated: a better way to do this.

       foreach ($order->get_items() as $item_id => $item_obj) { //loop through each rewnewal item

          $parent_id = $item_obj->get_parent_id(); // Get the parent order ID for the subscriptions.

          $parentSubscriptions = wcs_get_subscriptions_for_order( $parent_id );//get parent order subscriptions 
    
       foreach (  $parentSubscriptions->get_items() as $parent_item_id => $subscription_item_obj) { //loop through parent order items and get the meta. 
    
         $ParentCallinData = $subscription_item_obj->get_meta('call_in_data');
 
        // Store parenent item call in data in renewal order item meta
        wc_update_order_item_meta($item_id,'call_in_data',   $ParentCallinData, true);
 
     }
    }
   } 

   else {//if there is not a subscription renewal in the order then we run the API 

       foreach ($order->get_items() as $item_id => $item_obj) { 
         //Code here has been removed that builds and runs the API call to dynamically get the call-in data and store it in $APIresponse
         wc_update_order_item_meta($item_id,'call_in_data',  $APIresponse, true); //the APIresponse is added to an order item meta key. I need to insert this meta in each child subscription.
     }
    }
   }

0 个答案:

没有答案