user1381985
user1381985

Reputation: 75

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. 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.

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

Upvotes: 1

Views: 141

Answers (1)

Kairav Thakar
Kairav Thakar

Reputation: 1001

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);
}

Upvotes: 0

Related Questions