Add a fee for a specific product category in Woocommerce

后端 未结 2 1909
醉话见心
醉话见心 2020-12-21 23:55

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

2条回答
  •  粉色の甜心
    2020-12-22 00:05

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

提交回复
热议问题