在 WooCommerce 订阅续订订单中设置送货方式

问题描述 投票:0回答:1

当用户购买带有每月创建订单的定期选项的产品时,没有设置运输方式。只有父订单有运送方式,所有子订单都没有运送方式。

我想在创建经常性订单时将父运输方式添加到所有子订单。

这里的代码我尝试过但不起作用,我想在创建子订单时添加父级的送货方式。

add_action('woocommerce_new_order', 'add_colissimo_method', 10, 1);

function add_colissimo_method($order_id) {
    $order = wc_get_order($order_id);

  
    if ($order->get_shipping_method()) {
        return; 
    }


        $subscriptions = wcs_get_subscriptions_for_order($renewal_order_id);

        if (!empty($subscriptions)) {
    
            $parent_order_id = $subscriptions[0]->get_parent_id();

            if (!empty($parent_order_id)) {
                $parent_order = wc_get_order($parent_order_id);
                $parent_shipping_method = $parent_order->get_shipping_method();
                update_post_meta($renewal_order_id, '_shipping_method', $parent_shipping_method);
            }
     }

    $order->save();
    
}
php woocommerce methods orders woocommerce-subscriptions
1个回答
0
投票

您没有以正确的方式执行此操作,您需要使用 WC 订阅过滤器挂钩

尝试以下方法(代码已注释)

add_filter( 'wcs_new_order_created', 'add_shipping_items_to_renewal_orders', 10, 3 );
function add_shipping_items_to_renewal_orders( $order, $subscription, $type ) {
    // Targeting renewal orders only
    if ( $type === 'renewal_order' ) {
        // Get the parent order (initial order)
        $parent_order = $subscription->get_related_orders('all', 'parent');
        $parent_order = reset($parent_order);

        // Set the array for tax calculations
        $calculate_tax_for = array(
            'country'   => $parent_order->get_shipping_country(),
            'state'     => $parent_order->get_shipping_state(),
            'postcode'  => $parent_order->get_shipping_postcode(),
            'city'      => $parent_order->get_shipping_city(),
        );

        // Loop through parent order "shipping" items
        foreach( $parent_order->get_items('shipping') as $parent_item ) {
            $item  = new WC_Order_Item_Shipping(); // create a new empty order item "shipping"
            $item->set_method_title( $parent_item->get_method_title() ); // set the existing Shipping method title
            $item->set_method_id( $parent_item->get_method_id() ); // set an existing Shipping method rate ID
            $item->set_total( $parent_item->get_total() );  // set an existing Shipping method total
            $item->calculate_taxes( $calculate_tax_for );  // Calculate taxes for the item

            $order->add_item( $item ); // Add the shipping item to the renewal order
        }
        $order->calculate_totals(); // recalculate totals and save
    }
    return $order;
}

应该可以。

相关:添加更新或删除 WooCommerce 运输订单项目

© www.soinside.com 2019 - 2024. All rights reserved.