根据购物车数量和产品类别进行折扣 [英] Discount based on cart items count and product categories
问题描述
我正在尝试根据最小的购物车商品数量和类别添加自定义购物车折扣。
我已经从以下答案中获取了代码:
基于购物车商品数量的购物车折扣,仅适用于未售商品
I am trying to add a custom cart discount based on a minimal cart item count and categories.
I have take the code from this answer:
Cart discount based on cart item count and only for items that are not in sale
我对其做了一些更改,这是我的代码:
I have made some changes to it and this is my code:
add_action('woocommerce_cart_calculate_fees' , 'my_custom_discount', 10, 1);
function my_custom_discount( $cart_object ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only when there is 4 or more items in cart
if( $cart_object->get_cart_contents_count() >= 4):
// Defining variables
$categories = array('mycategory1','mycategory2');
$has_category = false;
// Iterating through each item in cart
foreach( $cart_object->get_cart() as $cart_item ){
// Getting an instance of the product object
$_product = new WC_Product( $cart_item['product_id'] );
// If a cart item has the category
if(has_category($category, $_product)){
$has_category = true;
break;
}
}
## Discount calculation ##
$discount = $cart_object->subtotal * -0.03;
## Applied discount (no products on sale) ##
if($has_category )
$cart_object->add_fee( '3% discount', $discount);
endif;
}
我无法使其正常运行。
I can’t make it work.
我在做错什么以及如何使其工作?
What I am doing wrong and How to make it work?
谢谢
推荐答案
由于产品类别是自定义分类法 'product_cat'
需要使用 has_term()
条件函数(而不是 has_category()
),方法是:
As product categories are a custom taxonomy 'product_cat'
you will need to use has_term()
conditional function (instead of has_category()
) this way:
add_action('woocommerce_cart_calculate_fees' , 'my_custom_discount', 10, 1);
function my_custom_discount( $cart_obj ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only when there is 4 or more items in cart
if ( $cart_obj->get_cart_contents_count() > 3):
// Set HERE your array of categories (slugs, IDs or names) <== <== <== <== <==
$categories = array('mycategory1','mycategory2');
// Initialising variable
$has_category = false;
// Iterating through each item in cart
foreach( $cart_obj->get_cart() as $cart_item ){
// The product ID
$product_id = $cart_item['product_id'];
// When a cart item is from one defined product categories we set $has_category to true.
if ( has_term( $categories, 'product_cat', $product_id ) ) {
$has_category = true;
break;
}
}
## Discount calculation ##
$discount = $cart_obj->subtotal * -0.03;
## Applied discount (for products (items) of defined product categories) ##
if( $has_category )
$cart_obj->add_fee( '3% discount', $discount);
endif;
}
此代码包含在活动子主题的function.php文件中(或主题),也可以在任何插件文件中。
此代码已经过测试,可用于WooCommerce 2.6+和3.0 +
This code is tested and works for WooCommerce version 2.6+ and 3.0+
这篇关于根据购物车数量和产品类别进行折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!