phpwordpresswoocommercecartfee

Add a fee for a specific product category in Woocommerce


I already found this code here and it works for like 80/90% for me (see below).

This code adds 60 euro to my cart when there is a product from category ID 349 in the cart. When I add a product from that category to my cart when the cart is empty it works fine. But when there is already a product in my cart from a different category and then I add the product with category 349 it doesn't add the 60 euro extra fee. How is this possible?

 function woo_add_cart_fee() {

$category_ID = '349';
global $woocommerce;

foreach ($woocommerce->cart->cart_contents as $key => $values ) {
    // Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
    // Because a product can have multiple categories, we need to iterate through the list of the products category for a match
    foreach ($terms as $term) {
        // 349 is the ID of the category for which we want to remove the payment gateway
        if($term->term_id == $category_ID){
         $excost = 60;
         }
         }
        $woocommerce->cart->add_fee('Extra bezorgkosten kunstgras', $excost, $taxable = false, $tax_class = '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );

Solution

  • The code you are using is a bit outdated and you should use has_term() Wordpress conditional function to target a product category this way:

    add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
    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('349');
        $fee_amount = 0;
    
        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item ){
            if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
                $fee_amount = 60;
        }
    
        // Adding the fee
        if ( $fee_amount > 0 ){
            // Last argument is related to enable tax (true or false)
            WC()->cart->add_fee( __( "Extra bezorgkosten kunstgras", "woocommerce" ), $fee_amount, false );
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.

    A fee of 60 will always be added if there is in cart an item from 349 product category ID.