我喜欢根据产品类别打折 Woocommerce 中最便宜的购物车商品。基于"Woocommerce 中成本较低的产品的购物车折扣 https://stackoverflow.com/questions/49693564/cart-discount-for-product-that-cost-less-in-woocommerce/49698427#49698427"完美运行的答案代码。
但如何使其仅适用于特定的产品类别。
这个想法是在购物车中有 2 种产品,并为特定产品类别的最便宜的产品提供折扣。
Updated- 限定产品类别中的 2 件商品。
以下将对特定产品类别执行相同的操作(将在代码中定义):
add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$categories = ['tshirts']; // Your product categories (coma separated)
$percentage = 10; // 10 % discount
// Only for 2 items or more
if ( $cart->get_cart_contents_count() < 2 ) return;
// Initialising
$discount = 0;
$item_prices = array();
// Loop though each cart items and set prices in an array
foreach ( $cart->get_cart() as $cart_item ) {
if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
}
}
// We set the fee for 2 items of the defined product category
if( count($product_prices_excl_tax) == 2 ) {
sort($product_prices_excl_tax);
$discount = reset($product_prices_excl_tax) * $percentage / 100;
$cart->add_fee( sprintf( __("Discount on cheapest %s"), '('.$percentage.'%)' ), -$discount );
}
}
代码位于活动子主题(或活动主题)的 function.php 文件中。它应该有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)