Original answer (In 2014)
©dothedew (user edited the question and answered in a question at that time)
<?php
// Add Service Fee to Category
function woo_add_cart_fee() {
$category_ID = '23';
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
// Get the terms, i.e. category list using the ID of the product
$terms = get_the_terms( $values['product_id'], 'product_cat' );
// Because a product can have multiple categories, we need to iterate through the list of the products category for a match
foreach ($terms as $term) {
// 23 is the ID of the category for which we want to remove the payment gateway
if($term->term_id == $category_ID){
$excost = 6;
}
}
$woocommerce->cart->add_fee('Service Charge', $excost, $taxable = false, $tax_class = '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
My answer (In 2023)
I've made some update in code using WooCommerce 3.x syntax:
- Instead of using $woocommerce, which is a global variable, I'm using WC() to get the WooCommerce instance. This is a more modern way of accessing the cart and other objects in WooCommerce.
- I've changed the way we loop through the cart items using WC()->cart->get_cart() instead of $woocommerce->cart->cart_contents.
- I'm using the $category_slug variable instead of $category_ID. This is a more user-friendly way of identifying a category and is less likely to change than the ID.
- I've move
add_fee
outside the loop
Answer :
<?php
/**
* Add service fee to a specific category
*/
function woo_add_cart_fee() {
// Define the category slug and service fee amount
$category_slug = 'category-slug';
$product_count = 0;
// Loop through each item in the cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Get the product ID and its categories
$product_id = $cart_item['product_id'];
$product_categories = get_the_terms( $product_id, 'product_cat' );
// Check if the product belongs to the specified category
if ( ! empty( $product_categories ) ) {
foreach ( $product_categories as $category ) {
if ( $category_slug === $category->slug ) {
$product_count++;
}
}
}
}
if ( $product_count > 0 ) {
$service_fee = 6 * $product_count;
// Add the service fee to the cart
WC()->cart->add_fee( __( 'Service Charge', 'woocommerce' ), $service_fee, false );
}
}
// Add the fee calculation function to the cart
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );