[英]Cart fee based on specific product category cart item quantity in Woocommerce
Inspired by this answer code , we are currently using some custom code that adds a $2.50
dollar fee when the Quantity equals 6
.受此答案代码的启发,我们目前正在使用一些自定义代码,当数量等于
6
时会增加$2.50
美元的费用。
However, we want it to add a $2.50
fee when two products in the same category have each a quantity of 6
.但是,当同一类别中的两个产品的数量均为
6
时,我们希望它增加$2.50
的费用。
It almost works, but when there are two products in the same category and one of them has a quantity of 12
then the code snippet instead of keeping the $fee_amout
to $2.50
, changes it to $7.50
.它几乎可以工作,但是当同一类别中有两种产品并且其中一种的数量为
12
时,代码片段不会将$fee_amout
保持为$2.50
,而是将其更改为$7.50
。
So we need to find a way to better target the individual products and their respective quantity or use or equation and -5 from it whenever it finds an instance of the product having a quantity of 12.因此,我们需要找到一种方法来更好地定位单个产品及其各自的数量或用途或方程式,并在找到数量为 12 的产品实例时从中得到 -5。
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
$categories = array('649');
$fee_amount = 0;
$cat_count = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
if( has_term( $categories, 'product_cat', $cart_item['product_id']))
$quantity = $cart_item['quantity'];
$cat_count += $cart_item['quantity'];
}
if ($quantity == 6){
$fee_amount = (2.5 * ($cat_count/6));
;}
// Adding the fee
if ( $fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Find-it Mixed Case", "woocommerce" ), $fee_amount, false );
}
}
Updated更新
If I have well understood, you want to add a fixed cart fee, when there is 2 items from a specific product category in cart that have each one a quantity greater or equal to 6.如果我很好理解,您想添加固定的购物车费用,当购物车中有来自特定产品类别的 2 件商品且每件商品的数量大于或等于 6 时。
Try the following code:试试下面的代码:
add_action( 'woocommerce_cart_calculate_fees', 'custom_cart_fee', 20, 1 );
function custom_cart_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
$categories = array('649');
// Initializing
$count = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
if( $cart_item['quantity'] >= 6 ){
$count++;
}
}
}
if ( $count >= 1 ) {
$fee_amount = 2.50 * $count;
$cart->add_fee( __( "Shipping fee", "woocommerce" ), $fee_amount, false );
// Last argument is related to enable tax (true or false)
}
}
Code goes in function.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 function.php 文件中。 Tested and works.
测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.