I'm trying to add a fee of £3 per product if any of the products in the basket have the category ID "160".
This is working great but I also only want this fee to apply if certain shipping methods are chosen.
What I have so far:
function df_add_ticket_surcharge( $cart_object ) {
global $woocommerce;
$specialfeecat = 160; // category id for the special fee
$spfee = 3.00; // initialize special fee
$spfeeperprod = 3.00; //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 * $quantiy;
}
}
endif;
}
if($spfee > 0 ) {
$woocommerce->cart->add_fee( 'Ticket Concierge Charge', $spfee, true, 'standard' );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );
I have tried integrating the function from this post: https://stackoverflow.com/a/47732732/12019310 but can't seem to get it functioning without a critical notice.
Any advice would be greatly appreciated!
The following code
function df_add_ticket_surcharge( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
$chosen_shipping_method = explode(':', $chosen_shipping_method_id)[0];
/* SETTINGS */
$special_fee_cat = 160; // category id for the special fee
$fee_per_prod = 3; //special fee per product
/* END SETTINGS */
// Total
$total = 0;
// Only for Local pickup chosen shipping method
if ( strpos( $chosen_shipping_method_id, 'local_pickup' ) !== false ) {
// Loop though each cart items and set prices in an array
foreach ( $cart->get_cart() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Quantity
$product_quantity = $cart_item['quantity'];
// Check for category
if ( has_term( $special_fee_cat, 'product_cat', $product_id ) ) {
$total += $fee_per_prod * $product_quantity;
}
}
// Add the discount
$cart->add_fee( __('Ticket Concierge Charge', 'woocommerce'), $total );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge', 10, 1 );