我在WooCommerce优惠券代码中创建了一个名为" 2FOR1WOW"并将此代码添加到functions.php但它无法正常工作。该票证已被应用,并且确认消息表明它已经可以,但总数不会减少。
非常感谢任何帮助!
// Hook before calculate fees - "Buy 2 get cheapest free" coupon
add_action('woocommerce_cart_calculate_fees' , 'buy2_coupon');
/**
* Add discount for "Buy 2 get cheapest free" coupon
* @param WC_Cart $cart
*/
function buy2_coupon( WC_Cart $cart ){
// add the coupons here
$buy2_coupons = array('2FOR1WOW', 'anothercouponcode');
// return if cart has less than 2 items
if( $cart->cart_contents_count < 2 ){
return;
}
$applied_coupons = $cart->get_applied_coupons();
$matches = array_intersect($buy2_coupons, $applied_coupons);
// return if no coupon matches
if (empty($matches)) return;
// loop through the items in cart to find the cheapest
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$product_price[] = $_product->get_price_including_tax();
}
$cheapest = min($product_price);
$cart->add_fee( 'Coupon 2FOR1WOW', -$cheapest, true, 'standard' );
}
答案 0 :(得分:0)
自WooCommerce 3+以来,WC_Product get_price_including_tax()
已被弃用,并已被函数wc_get_price_excluding_tax()
取代(不再是方法)。
您应该不需要任何优惠券代码来使这种代码正常工作。当你使用它们来解雇这个折扣“买一送一”时,我将它保留在下面的功能中。
您在代码中遗忘的内容是:
min()
php函数只能在一个项目上运行,所以它并没有真正适用。
所以正确的代码应该是这样的:
add_action('woocommerce_cart_calculate_fees', 'buy_one_get_one_free', 10, 1 );
function buy_one_get_one_free( $wc_cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$cart_item_count = $wc_cart->get_cart_contents_count();
if ( $cart_item_count < 2 ) return;
// Set HERE your coupon codes
$coupons_codes = array('2for1wow', 'anothercouponcode');
$discount = 0; // initializing
$matches = array_intersect( $coupons_codes, $wc_cart->get_applied_coupons() );
if( count($matches) == 0 ) return;
// Iterating through cart items
foreach ( $wc_cart->get_cart() as $key => $cart_item ) {
$qty = intval( $cart_item['quantity'] );
// Iterating through item quantities
for( $i = 0; $i < $qty; $i++ )
$items_prices[] = floatval( wc_get_price_excluding_tax( $cart_item['data'] ) );
}
asort($items_prices); // Sorting cheapest prices first
// Get the number of free items (detecting odd or even number of prices)
if( $cart_item_count % 2 == 0 ) $free_item_count = $cart_item_count / 2;
else $free_item_count = ($cart_item_count - 1) / 2;
// keeping only the cheapest free items prices in the array
$free_item_prices = array_slice($items_prices, 0, $free_item_count);
// summing prices for this free items
foreach( $free_item_prices as $key => $item_price )
$discount -= $item_price;
if( $discount != 0 ){
// The discount
$label = '"'.reset($matches).'" '.__("discount");
$wc_cart->add_fee( $label, number_format( $discount, 2 ), true, 'standard' );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
此代码在Woocommerce 3+上进行测试并正常运行。你会得到类似的东西:
优惠券代码(此处
2for1wow
)需要以零价格折扣创建。当优惠券应用于购物车时,启用了负费用(折扣)并将一个项目释放为两个。