首页 > 解决方案 > 基于 Woocommerce 中的运输等级和最低金额的有条件免费送货

问题描述

在有关运输方法的 woocommerce 中,我试图拥有以下内容:

我尝试过使用统一费率和运费等级,如果产品 A 和产品 B 在那里,那么如果购物车没有达到 200,则需要 15 运费。

任何帮助表示赞赏。

标签: phpwordpresswoocommercecartshipping-method

解决方案


更新:要使其首先工作,您将需要:

  • 要添加“免费”运输类别(第一)
  • 要启用 2 种运输方式:“免费送货”和“统一费率”,
  • 在您的免费送货产品中,需要设置送货类别“免费”
  • 在您的其他产品中将没有任何定义的运输类别
  1. 对于“免费送货”方式,您不会对其添加任何限制

  2. 对于“统一费率”运输方式,您将按照以下屏幕截图进行设置:

在此处输入图像描述

  1. 魔术将由以下代码完成,其余部分将完成:

    add_filter('woocommerce_package_rates', 'conditional_free_shipping', 10, 2); function conditional_free_shipping( $rates, $package ){ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return $rates;

     ## -- Your settings below -- ##
    
     $shipping_class  = 'free'; // "Free" shipping class products
     $min_free_amount = 200;    // Minimal Free shipping amount for normal products
    
     ## -- -- -- -- -- -- -- -- -- ##
    
     $has_free = false; // Initializing
     $products_total = 0; // Initializing
    
     // Loop through cart items
     foreach( $package['contents'] as $cart_item ) {
         if( $cart_item['data']->get_shipping_class() == $shipping_class ) {
             $has_free = true;
         } else {
             // Get the total purchased amount for normal product
             $products_total += $cart_item['line_total'] + $cart_item['line_tax'];
         }
     }
    
     foreach ( $rates as $rate_key => $rate ){
         // 1. Only Free shipping products in cart OR both products kind in cart
         if( $has_free ) {
             if( 'flat_rate' === $rate->method_id )
                 unset( $rates[$rate_key] ); // Remove flat rate
         }
         // 2. Only normal products in cart
         else {
             // A. If it's under the min amount
             if( 'free_shipping' === $rate->method_id && $products_total < $min_free_amount )
                 unset( $rates[$rate_key] ); // Remove Free shipping
             // B. When min amount is reached
             elseif( 'flat_rate' === $rate->method_id && $products_total >= $min_free_amount )
                 unset( $rates[$rate_key] ); // Remove flat rate
         }
     }
     return $rates;
    

    }

代码在您的活动子主题(活动主题)的 function.php 文件中。测试和工作。

您可能需要刷新运输缓存数据:在 Woocommerce 运输设置中禁用、保存和启用、保存当前运输区域的相关运输方式。


推荐阅读