Osm*_*man 5 php wordpress cart discount woocommerce
在WooCommerce中,我想特别针对那些没有销售的产品给予10%的折扣.如果购物车商品数量为5件或更多商品而非销售,那么我给予10%的折扣.
我使用以下代码根据购物车项目计数限制获得折扣:
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
/**
* Add custom fee if more than three article
* @param WC_Cart $cart
*/
function add_custom_fees( WC_Cart $cart ){
if( $cart->cart_contents_count < 5 ){
return;
}
// Calculate the amount to reduce
$discount = $cart->subtotal * 0.1;
$cart->add_fee( '10% discount', -$discount);
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何仅对未售出的商品应用折扣.我怎样才能实现它?
谢谢.
这是一个自定义挂钩函数,如果购物车中有 5 件或更多商品且没有商品在售,则该函数将应用于购物车折扣:
add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only when there is 5 or more items in cart
if( $cart->get_cart_contents_count() >= 5):
// Initialising variable
$is_on_sale = false;
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
// Getting an instance of the product object
$product = $cart_item['data'];
// If a cart item is on sale, $is_on_sale is true and we stop the loop
if($product->is_on_sale()){
$is_on_sale = true;
break;
}
}
## Discount calculation ##
$discount = $cart->subtotal * -0.1;
## Applied discount (no products on sale) ##
if(!$is_on_sale )
$cart->add_fee( '10% discount', $discount);
endif;
}
Run Code Online (Sandbox Code Playgroud)
此代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
这段代码已经过测试并且运行良好。