1 回答

TA貢獻1824條經驗 獲得超8個贊
使用WooCommerce - 當免費送貨可用時隱藏其他送貨方式現有答案代碼,您只需使用以下方式計算不同的訂單項目:
$items_count?=?count(WC()->cart->get_cart());
現在,您需要將免費送貨方式設置設置為
N/A
?(第一個選項);
然后您將能夠輕松地更改代碼以允許免費送貨,如下所示:
add_filter( 'woocommerce_package_rates', 'free_shipping_on_items_count_threshold', 100, 2 );
function free_shipping_on_items_count_threshold( $rates, $package ) {
? ? $items_count? ? ?= count(WC()->cart->get_cart()); // Different item count
? ? $items_threshold = 4; // Minimal number of items to get free shipping
? ? $free? ? ? ? ? ? = array(); // Initializing
? ? // Loop through shipping rates
? ? foreach ( $rates as $rate_id => $rate ) {
? ? ? ? // Find the free shipping method
? ? ? ? if ( 'free_shipping' === $rate->method_id ) {
? ? ? ? ? ? if( $items_count >= $items_threshold ) {
? ? ? ? ? ? ? ? $free[ $rate_id ] = $rate; // Keep only "free shipping"
? ? ? ? ? ? } elseif ( $items_count < $items_threshold ) {
? ? ? ? ? ? ? ? unset($rates[$rate_id]); // Remove "Free shipping"
? ? ? ? ? ? }
? ? ? ? ? ? break;// stop the loop
? ? ? ? }
? ? }
? ? return ! empty( $free ) ? $free : $rates;
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。
如果您也想允許優惠券設置免費送貨,則必須將免費送貨設置更改為“最低訂單金額或優惠券”并設置0最低訂單金額,請改為使用以下內容:
add_filter( 'woocommerce_package_rates', 'free_shipping_on_items_count_threshold', 100, 2 );
function free_shipping_on_items_count_threshold( $rates, $package ) {
? ? $items_count? ? ? = count(WC()->cart->get_cart()); // Different item count
? ? $items_threshold? = 4; // Minimal number of items to get free shipping
? ? $coupon_free_ship = false; // Initializing
? ? $free? ? ? ? ? ? ?= array(); // Initializing
? ? // Loop through applied coupons
? ? foreach( WC()->cart->get_applied_coupons() as $coupon_code ) {
? ? ? ? $coupon = new WC_Coupon( $coupon_code ); // Get the WC_Coupon Object
? ? ? ? if ( $coupon->get_free_shipping() ) {
? ? ? ? ? ? $coupon_free_ship = true;
? ? ? ? ? ? break;
? ? ? ? }
? ? }
? ? // Loop through shipping rates
? ? foreach ( $rates as $rate_id => $rate ) {
? ? ? ? // Find the free shipping method
? ? ? ? if ( 'free_shipping' === $rate->method_id ) {
? ? ? ? ? ? if( $items_count >= $items_threshold || $coupon_free_ship ) {
? ? ? ? ? ? ? ? $free[ $rate_id ] = $rate; // Keep only "free shipping"
? ? ? ? ? ? } elseif ( $items_count < $items_threshold ) {
? ? ? ? ? ? ? ? unset($rates[$rate_id]); // Remove "Free shipping"
? ? ? ? ? ? }
? ? ? ? ? ? break;// stop the loop
? ? ? ? }
? ? }
? ? return ! empty( $free ) ? $free : $rates;
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。
刷新運輸緩存:
此代碼已保存在您的 function.php 文件中。
在運輸區域設置中,禁用/保存任何運輸方式,然后啟用返回/保存。
你已經完成了,你可以測試它。
- 1 回答
- 0 關注
- 166 瀏覽
添加回答
舉報