[英]WooCommerce checkout fee based on cart item count with category excluded
I am trying to make custom checkout fees if there is more items in cart than 5 or 10, but I also have to exclude categories "tickets" and "vouchers" from count.如果购物车中的商品多于 5 或 10,我将尝试收取自定义结账费用,但我还必须从计数中排除类别“门票”和“代金券”。 I found good code examples but none with a negative category selection and I really don't want to set the rules manually for all my 20+ categories like in this post , it would be best to apply it for all EXCEPT an array of 2 categories.
我找到了很好的代码示例,但没有一个带有负面类别选择,我真的不想像这篇文章中那样为我的所有 20 多个类别手动设置规则,最好将它应用于除 2 个类别的数组之外的所有类别.
Here is my code that doesn't work:这是我的代码不起作用:
add_action( 'woocommerce_cart_calculate_fees','woocommerce_cart_extra_cost', 10, 1 );
function woocommerce_cart_extra_cost( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Below your category term ids, slugs or names to be excluded
$excluded_terms = array('tickets', 'vouchers');
$cart_item_count = 0; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
// Excluding some product category from the count
if ( ! has_term( $excluded_terms, 'product_cat', $item['product_id'] ) ) {
$items_count += $item['quantity'];
}
}
// CONDITIONAL ITEMS QUANTITY FEE AMOUNT
if( $cart_item_count < 6 )
$fee = 0;
elseif( $cart_item_count >= 6 && $cart_item_count < 11 )
$fee = 3;
elseif( $cart_item_count >= 11 )
$fee = 5;
if( $fee > 0 )
$cart->add_fee( __( "Handling Fee", "woocommerce" ), $fee, true);
}
What's wrong with it?它出什么问题了? Any code corrections will be greatly appreciated.
任何代码更正将不胜感激。 Thank you.
谢谢你。
Edit: I ended up using this answer: WooCommerce Quick cart fee编辑:我最终使用了这个答案: WooCommerce 快速购物车费用
Can you please try below code, I have revised your code little bit:你能试试下面的代码吗,我已经稍微修改了你的代码:
add_action( 'woocommerce_cart_calculate_fees','woocommerce_cart_extra_cost', 10, 1 );
function woocommerce_cart_extra_cost( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Below your category term ids, slugs or names to be excluded
$excluded_terms = array('tickets', 'vouchers');
$fee = 0;
$cart_item_count = count( WC()->cart->get_cart() ); // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
// Excluding some product category from the count
if ( has_term( $excluded_terms, 'product_cat', $item['product_id'] ) ) {
$cart_item_count = $cart_item_count - 1;
}
}
// CONDITIONAL ITEMS QUANTITY FEE AMOUNT
if( $cart_item_count < 2 )
$fee = 6;
elseif( $cart_item_count >= 6 && $cart_item_count < 11 )
$fee = 3;
elseif( $cart_item_count >= 11 )
$fee = 5;
if( $fee > 0 )
$cart->add_fee( __( "Handling Fee", "woocommerce" ), $fee, true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.