This question is an exact duplicate of:
Problem: Add_action code determines if "food" category in cart and applies delivery fee. Works perfectly but before fee applied, need customer to check if catering order needs delivery. If true, add fee.
Goal is to determine if "food" in cart," which current code does, and if true, show checkbox labelled Deliver Catering Order? [ ]. If true, adds fee on same row in cart before totals.
I worked on code to add row to Cart before totals but get fatal error. If I get add row code working, can I insert into add_action custom fee code after the loop through cart but before condition to apply fee.
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('food');
$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 = 25;
}
// Adding the fee
if ( $fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Delivery Fee", "woocommerce" ), $fee_amount,
false );
}
}
I expect the action to determine if "food" slug in cart, and if true, add row to cart before totals with customer input box to indicate if order delivery. If true, $25 fee added to same new row?
</div>