"add a fee to woocommerce per product, based on category" Answer’s

0

I was having the same issue and came across a code snippet that set me on the correct path. For the life of me, I cannot find the original site that housed the snippet, but here is my reworked version.

function df_add_ticket_surcharge( $cart_object ) {

    global $woocommerce;
    $specialfeecat = 86; // category id for the special fee
    $spfee = 0.00; // initialize special fee
    $spfeeperprod = 0.05; //special fee per product

    foreach ( $cart_object->cart_contents as $key => $value ) {

        $proid = $value['product_id']; //get the product id from cart
        $quantiy = $value['quantity']; //get quantity from cart
        $itmprice = $value['data']->price; //get product price

        $terms = get_the_terms( $proid, 'product_cat' ); //get taxonamy of the prducts
        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                $catid = $term->term_id;
                if($specialfeecat == $catid ) {
                    $spfee = $spfee + $itmprice * $quantiy * $spfeeperprod;
                }
            }
        endif;  
    }

    if($spfee > 0 ) {

        $woocommerce->cart->add_fee( 'Ticket Concierge Charge', $spfee, true, 'standard' );
    }

}

add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );

This will add a 5% surcharge to each item in the cart with the category of ticket (id: 86). I hope this helps you out, if you have not found a solution already.

Wednesday, March 31, 2021
 
TMichel
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share