今天的目标是检查具有特定运输类的产品是否在购物车中,因此如果是真的,则禁用免费送货。这是非常有用的,当有多个项目在购物车,您不想给免费送货某些订单。

WooCommerce:如果特定的货运类在购物车中,请禁用免费送货

WooCommerce Snippet(版本 2.6+):禁用免费送货(对于特定运送区域)如果购物车具有特定运送类别的产品

/**
 * @snippet       Disable Free Shipping if Cart has Shipping Class (WooCommerce 2.6+)

 * @sourcecode    https://businessbloomer.com/?p=19960
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 2.6.1
 */

add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_free_shipping_for_shipping_class', 10, 2 );
 
function businessbloomer_hide_free_shipping_for_shipping_class( $rates, $package ) {
$shipping_class_target = 15; // shipping class ID (to find it, see screenshot below)
$in_cart = false;
foreach( WC()->cart->cart_contents as $key => $values ) {
 if( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
  $in_cart = true;
  break;
 } 
}
if( $in_cart ) {
 unset( $rates['free_shipping:8'] ); // shipping method with ID (to find it, see screenshot below)
}
return $rates;
}

WooCommerce Snippet (version 2.5 and below): Disable Free Shipping if Cart has Product with Specific Shipping Class

/**
 * @snippet       Disable Free Shipping if Cart has Shipping Class

 * @sourcecode    https://businessbloomer.com/?p=19960
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 2.5.2
 */

add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_free_shipping_for_shipping_class', 10, 2 );
 
function businessbloomer_hide_free_shipping_for_shipping_class( $rates, $package ) {
$shipping_class_target = 15; // shipping class ID (to find it, see screenshot below)
$in_cart = false;
foreach( WC()->cart->cart_contents as $key => $values ) {
 if( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
  $in_cart = true;
  break;
 } 
}
if( $in_cart ) unset( $rates['free_shipping'] );
return $rates;
}

WooCommerce: How to Find Shipping Class ID (Woo 2.6+, after the introduction of the new Shipping Zones)

WooCommerce 2.6+: Find Shipping Class ID

WooCommerce: How to Find Shipping Method ID (Woo 2.6+, after the introduction of the new Shipping Zones)

Find Shipping Method Name in WooCommerce 2.6+

WooCommerce: How to Find Shipping Class ID (Woo 2.5 and below)

WooCommerce: Find Shipping Class ID


可以在哪里添加此代码?

您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到主题的 style.css 文件底部),修改之前建议先备份原始文件,若出现错误请先删除此代码。


这段代码是否正常可用?

或是您有更好的解决方案想要分享?请到薇晓朵 WooCommerce 中文论坛 留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。

需要关于 WooCommerce 的帮助 ?

请观看我们提供的免费视频教程或到薇晓朵 WooCommerce 中文论坛提问,会有专业技术团队提供相关帮助。