【发布时间】:2021-01-15 21:47:36
【问题描述】:
基于 Add an additional cost to flat rate shipping each 3 items in Woocommerce 回答代码,我进行了一些更改,以将额外费用添加到固定的运输方式,每 2 件(而不是每 3 件)并且仅在有专门的物品时来自特定类别(此处为“T 恤”类别)。
这是我的代码尝试:
// add X amount to shipping for every 2 items added to the cart (flat rate only)
add_filter('woocommerce_package_rates', 'shipping_additional_cost_each_three_items', 100, 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 = 8.40;
$items_count = WC()->cart->get_cart_contents_count();
// Define/replace here your correct category slug (!)
$product_category = 't-shirts';
$prod_cat = false;
// Going through each item in cart to see if there is anyone of your category
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
if ( has_term( $product_category, 'product_cat', $product_id ) ){
$prod_cat = true;
}
}
// 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 the additional cost if product in T-Shirt category after every 2 items (3, 6, 9 …)
if ( $prod_cat ) {
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;
}
}
对于选择的“统一费率”运输方式,当“T 恤”类别的商品在购物车中时,代码可以正常工作。但如果有不属于“t-shirt”类别的商品,价格就会消失并显示没有金额的标题。
谁能告诉我必须在哪里放置条件“如果类别为 X”,以使该代码正常运行?
【问题讨论】:
-
请等待您对以下答案的反馈
标签: php wordpress woocommerce taxonomy-terms shipping-method