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

标签 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

        }

    }

}

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

最佳答案

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

因此,在上面的代码片段中,我更改了...

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

...到...

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

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

关于php - WooCommerce - 如何在 calculate_shipping 函数中获取购物车商品的运输类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765743/

相关文章:

javascript - 静态定位菜单和 z-index 问题,需要保留我的 jquery 动画

php - 在 Woocommerce 3 中以编程方式向订单添加运费

php - 在正常价格之前显示销售价格 (WooCommerce)

php - 使用 php 进行有效的表单处理

php - 通过 PHP 将 Sql 数据库转换为具有正确格式的 JSON,并在 PHP 脚本本身中对值进行排序

php - C++程序调用PHP脚本上传内容到数据库

javascript getelementsByClassName - 未定义 []

php - 在单个产品页面上添加一个复选框,这会在 Woocommerce 中增加额外费用

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 将纯 PHP 代码转换为 codeigniter