我有一家商店的类别使用“虚拟”产品类型以避免运输。但是,每个包含该类别产品的订单都需要收取服务费。
通过各种搜索,我找到了不同的方式来全局添加费用,或根据数量添加费用,并尝试使用它来通过类别进行定位,但似乎无法正确完成。
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' );
©dothedew(用户编辑问题并在当时的问题中回答)
<?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' );
我使用 WooCommerce 3.x 语法对代码进行了一些更新:
add_fee
在循环外答案:
<?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' );