WooCommerce - 如何在calculate_shipping函数中获得购物车物品的运输类别?

ban*_*ing 6 php wordpress woocommerce

我创建了一个WooCommerce插件,为订阅者提供免费送货服务.在最近的WooCommerce升级后,它似乎已经破裂.

具体而言,问题似乎是可能无法正确检索购物车物品的运输类别.

这是我的calculate_shipping代码 - 任何人都可以建议什么是错的?

/**
 * Add free shipping option for customers in base country with an active subscription,
 * but only if the cart doesn't contain an item with the 'heavy-item-shipping-class'.
 *
 * @access public
 * @param mixed $package
 * @return void
 */
public function calculate_shipping($package) {

    global $woocommerce;

    // Check country and subscription status
    if (is_user_in_base_country() && does_user_have_active_subscription()) {

        // This flag will be set to TRUE if cart contains heavy items
        $disable_free_shipping = FALSE;

        // Get cart items
        $cart_items = $package['contents'];

        // Check all cart items
        foreach ($cart_items as $cart_item) {

            // Get shipping class
            $shipping_class = $cart_item['data']->shipping_class; // *** IS THIS THE RIGHT WAY TO GET THE SHIPPING CLASS ??? ***

            // If heavy item, set flag so free shipping option is not made available
            if ($shipping_class === 'heavy-item-shipping-class') {

                // Set flag
                $disable_free_shipping = TRUE;

                // Enough
                break;

            }

        }

        // If appropriate, add the free shipping option
        if ($disable_free_shipping === FALSE) {

            // Create the new rate
            $rate = array(
                'id' => $this->id,
                'label' => "Free Shipping",
                'cost' => '0',
                'taxes' => '',
                'calc_tax' => 'per_order'
            );

            // Register the rate
            $this->add_rate($rate);

        }
        else {

            // Doesn't qualify for free shipping, so do nothing

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

更新 我看了一下%package数组并注意到它现在包含了运输类[shipping_class:protected].(以前,这肯定是[shipping_class].)是否有可能提取这些数据?如果没有,这样做的正确方法是什么?

ban*_*ing 11

我找到了解决方案.现在,似乎获得产品/物品的运输类别的唯一方法是调用get_shipping_class()它.

所以,在我上面的代码片段中,我改变了......

$shipping_class = $cart_item['data']->shipping_class;

...至...

$shipping_class = $cart_item['data']->get_shipping_class();

希望,这将有助于其他人.:)