The tax is a tip which is a percentage the customer chooses of the cart totals, but it should only calculate the totals for one category (food) and exclude another (event tickets).
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if ( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $post_data );
} else {
$post_data = $_POST;
}
if (isset($post_data['propina'])) {
global $woocommerce;
$porcentaje = $post_data['propina'] / 100;
$propina = ( $woocommerce->cart->cart_contents_total ) * $porcentaje;
WC()->cart->add_fee( 'Propina Sugerida:', $propina );
}
}
In a few words, ( $woocommerce->cart->cart_contents_total - total price amount of event tickets ) * percentage
EDIT: I think I found the solution, but i have problems when the product is a variation
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if ( isset( $_POST['post_data'] ) ) {
parse_str( $_POST['post_data'], $post_data );
} else {
$post_data = $_POST;
}
if (isset($post_data['propina'])) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$product_in_cart = false;
$ticketpamount = 0;
foreach($items as $item => $values) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ( $_categoryid === 122 ) {
//category is in cart!
$price = get_post_meta($values['product_id'] , '_price', true);
$ticketpamount += $price;
$product_in_cart = true;
}
}
}
$porcentaje = $post_data['propina'] / 100;
if ( $product_in_cart ) {
$propina = ( $woocommerce->cart->cart_contents_total - $ticketpamount ) * $porcentaje;
} else {
$propina = ( $woocommerce->cart->cart_contents_total ) * $porcentaje;
}
WC()->cart->add_fee( 'Propina Sugerida:', $propina );
}
}