根据产品类别向woocommerce添加费用

dot*_*dew 5 wordpress woocommerce

因此,我开了一家商店,其类别使用“虚拟”产品类型以避免运输。但是,需要向包含该类别产品的每个订单添加服务费。

通过各种搜索,我找到了不同的方法来全局添加费用,或基于数量添加费用,并尝试使用分类来定位费用,但似乎做对了。任何帮助,将不胜感激。

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' );
Run Code Online (Sandbox Code Playgroud)

好的,因为这是我的第一篇文章,所以我暂时无法回答自己的问题。我终于将其与以下代码段配合使用,但是如果发现问题,请随时进行改进:

// 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' );
Run Code Online (Sandbox Code Playgroud)

您显然可以将类别ID和成本更改为所需的任何值。