【问题标题】:Hide free shipping when subtotal is greater than 0 in WooCommerce在 WooCommerce 中小计大于 0 时隐藏免费送货
【发布时间】:2021-08-13 12:57:23
【问题描述】:

我正在为 WooCommerce 插件使用免费产品样品,并尝试仅为样品产品设置有条件的免费送货,样品产品成本为 0,因此我试图隐藏免费送货,除非订单小计金额为 0。

简而言之:

我只想为样品产品提供免费送货服务,并且免费送货方式应该只对小计 = 0 的产品可见

进一步说明的屏幕截图:


我尝试的代码:

function ts_hide_shipping_for_order_total( $rates ) {
  $rate = array();
  $order_total = WC()->cart->get_subtotal();
  
  if( $order_total > 0 ) {
    foreach ( $rates as $rate_id => $rate ) {
      if ( 'free_shipping:20' === $rate->get_method_id() ) {
        $rate[ $rate_id ] = $rate;
      }
    }
  }
  return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_for_order_total', 100 );

add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
function hide_shipping_except_local_when_free_is_available($rates) {
    $free = $local = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping:20' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
        }
    }
    return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
}

但是这两个代码都没有给我想要的结果。谁能指出我正确的方向?

【问题讨论】:

    标签: php woocommerce cart subtotal shipping-method


    【解决方案1】:

    要隐藏/取消设置“免运费”,只要小计大于0,就可以使用下面的。

    所以你得到:

    function filter_woocommerce_package_rates( $rates, $package ) {
        // Get subtotal
        $subtotal = $package['cart_subtotal'];
        
        // Hide free shipping if subtotal > 0
        if ( $subtotal > 0 ) {
            // Loop trough
            foreach ( $rates as $rate_id => $rate ) {
                if ( $rate->method_id === 'free_shipping' ) {
                    unset( $rates[$rate_id] );
                }
            }   
        }
        
        return $rates;
    }
    add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
    

    附加问题:小计

    function filter_woocommerce_package_rates( $rates, $package ) { 
        // Get subtotal
        $subtotal = $package['cart_subtotal'];
        
        // Loop trough
        foreach ( $rates as $rate_id => $rate ) {
            if ( $rate->method_id === 'free_shipping' ) {
                // Hide free shipping if subtotal > 0
                if ( $subtotal > 0 ) {
                    unset( $rates[$rate_id] );
                }
            } else {
                // Hide other methods when subtotal <= 0
                if ( $subtotal <= 0 ) {
                    unset( $rates[$rate_id] );
                }               
            }
        }
        
        return $rates;
    }
    add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
    

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 2020-11-05
      • 2020-06-22
      • 2016-11-11
      • 2018-08-09
      • 2020-12-03
      • 1970-01-01
      • 2018-03-05
      相关资源
      最近更新 更多