Cart discount based on cart item count and only for items that are not in sale(购物车折扣基于购物车商品数量且仅适用于未销售的商品)
问题描述
在 WooCommerce 中,我想专门为那些未销售的产品提供 10% 的折扣.如果购物车中的商品数量为 5 件或更多商品并且没有打折,那么我会提供 10% 的折扣.
In WooCommerce, I would like to give a discount of 10% specifically for those products that are not on sale. If cart item count is 5 or more items and not on sale, then I give a discount of 10%.
我使用以下代码根据此处的购物车商品数量限制获得折扣:
I use the following code to get a discount based on cart item count restriction here:
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);
}
但我不知道如何仅对非销售商品应用折扣.我怎样才能实现它?
But I don't know how to apply the discount only for items that are not in sale. How can I achieve it?
谢谢.
推荐答案
这是一个自定义挂钩函数,如果购物车中有 5 件或更多商品且没有产品,则该函数将应用于购物车 折扣特价:
Here is a custom hooked function that will apply to cart a discount, if there is 5 or more items in cart and no products on sale:
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;
}
此代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.
此代码已经过测试并且运行良好.
This code is tested and works perfectly.
这篇关于购物车折扣基于购物车商品数量且仅适用于未销售的商品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:购物车折扣基于购物车商品数量且仅适用于未销
基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01