Add a fee to woocommerce by product category

So, I have a store with a category that uses the type of “virtual” product to avoid delivery. However, there is a service charge that must be added to each order that includes a product in this category.

Through various searches, I found different ways to globally add a fee or add a fee based on quantity, and tried to use it to target through a category, but it doesn't seem to be that way. Any help would be appreciated.

function woo_add_cart_fee() {
global $woocommerce;
//Getting Cart Contents. 
$cart = $woocommerce->cart->get_cart();
//find product category
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );
    }
  if ($_categoryid == 23){
      $excost = 6;
  } 
  elseif ($_categoryid == 14){
      $excost = 0;
  }     

$woocommerce->cart->add_fee('Service Charge', $excost, $taxable = false, $tax_class = '');
}   
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );

Well, since this was my first post, I can’t answer my question for a while. I finally got this to work with the following snippet, but feel free to improve if you find problems:

// 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' );

, , .

+4

Source: https://habr.com/ru/post/1540263/


All Articles