【问题标题】:WooCommerce - How to get shipping class of cart items in calculate_shipping function?WooCommerce - 如何在 calculate_shipping 函数中获取购物车物品的运输类别?
【发布时间】:2015-02-27 13:00:18
【问题描述】:

我创建了一个 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

        }

    }

}

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

【问题讨论】:

  • 什么是$package?那是一个 WC 订单对象吗?
  • 不,它只是一个普通数组,由 WooCommerce 作为参数传递给 calculate_shipping 函数。根据docs.woocommerce.com/wc-apidocs/class-WC_Shipping.html,它是一个用于计算运费的购物车物品的多维数组。

标签: php wordpress woocommerce


【解决方案1】:

我找到了解决方案。现在,获得产品/项目的运输类别的唯一方法似乎是致电get_shipping_class()。

所以,在我上面的代码 sn-p 中,我改变了...

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

...到...

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

希望这对其他人有所帮助。 :)

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多