Следующий код добавит дополнительную стоимость к методу доставки по фиксированной ставке каждые 3 элемента (3, 6, 9…) .
Вам потребуется изменить стоимость доставки , указав простую начальную стоимость вместо формулы.
Вам может потребоваться «Включить режим отладки» в общих настройках доставки на вкладке «Параметры доставки», чтобы временно отключить кэши доставки.
Код (где вы будете устанавливать дополнительную стоимость доставки) :
add_filter('woocommerce_package_rates', 'shipping_additional_cost_each_three_items', 12, 2);
function shipping_additional_cost_each_three_items( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE set your additional shipping cost
$additional_cost = 1.25;
$items_count = WC()->cart->get_cart_contents_count();
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targetting "flat rate"
if( 'flat_rate' === $rate->method_id ){
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Adding to cost the additional cost each 3 items (3, 6, 9 …)
for($i = 0; $i <= $items_count; $i+=3){
$new_cost += $additional_cost;
}
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.
Не забудьте отключить опцию «Включить режим отладки» в настройках доставки.
Ответ на основании вашего второго комментария:
вы замените этот блок:
// Adding to cost the additional cost each 3 items (3, 6, 9 …)
for($i = 0; $i <= $items_count; $i+=3){
$new_cost += $additional_cost;
}
следующим:
// Adding to cost an additional fixed cost for the 2nd item
if($items_count >= 2){
$new_cost += 6.21;
}
// Adding to cost the additional cost each 3 items (3, 6, 9 …)
for($i = 0; $i <= $items_count; $i+=3){
$new_cost += $additional_cost;
}