WooCommerce -为某些产品添加免费送货,当购物车达到一定数量时


WooCommerce - Add free shipping for certain products and when the cart which reaches an amount

我在WooCommerce上经营一家网上商店,销售普通产品和书籍。我想达到以下目标:

  • 如果某人的购物车值为<他应该支付运费>
  • 如果某人的购物车值> 50,运费应该是免费的
  • 如果有人将一本书添加到购物车中,运费总是免费的

我尝试用下面的代码:

   function custom_free_per_class( $return, $package ) {
        // Setup an array of shipping classes that allow Flat Rate Shipping
        $shippingclass_array = array( 'bookshipping');
        // loop through the cart checking the shipping classes
        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $shipping_class = get_the_terms( $values['product_id'], 'product_shipping_class' );
            if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass_array ) ) {
                return true;
                break;
            }//if
        }//foreach
    }//function
    add_filter( 'woocommerce_shipping_free_shipping_is_available', 'custom_free_per_class', 10, 2 );
    add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
    /**
    * Hide shipping rates when free shipping is available
    *
    * @param array $rates Array of rates found for the package
    * @param array $package The package array/object being shipped
    * @return array of modified rates
    */
    function hide_shipping_when_free_is_available( $rates, $package ) {
    // Only modify rates if free_shipping is present
    if ( isset( $rates['free_shipping'] ) ) {
        // To unset all methods except for free_shipping, do the following
        $free_shipping = $rates['free_shipping'];
        $rates = array();
        $rates['free_shipping'] = $free_shipping;
    }
        return $rates;
    }

我在WooCommerce后端设置了购物车值达到50后应该可以免费送货。但是这行不通。上面的代码工作-所以当有人添加一本书时保证免费送货,但这似乎阻碍了其他意图(购物车> 50)的工作。如果我删除代码

add_filter( 'woocommerce_shipping_free_shipping_is_available', 'custom_free_per_class', 10, 2 );

当达到50时增加免费送货的功能是有效的,但肯定的是书籍不再是免费的了。

有没有人知道这里出了什么问题?如果有人能帮助我,我将非常感激。

谢谢!

我自己解决了。函数的输入参数不是($return, $package),而是($is_available)。