【发布时间】:2020-06-02 14:40:14
【问题描述】:
我已经尝试了一段时间来使其正常工作,但我还没有找到任何可以完全满足我们需要的解决方案,而且我离 PHP 专家还很远,所以我有点迷茫。
我们使用 WooCommerce 和 WooTickets。目标是仅对“门票”类别 (ID:34) 中的产品添加 5% 的“服务费”费用。
我们发现了这个代码剪辑器,它会根据产品类别添加固定成本:
// 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 Fee', $excost, $taxable = false, $tax_class = '');
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
这个解决方案的主要问题是它增加了固定成本,而我们需要一个百分比成本。
我们还从 WooThemes 自己找到了这段代码 sn-p:
/**
* Add a 1% surcharge to your cart / checkout
* change the $percentage to set the surcharge to a value to suit
* Uses the WooCommerce fees API
*
* Add to theme functions.php
*/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 0.05;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Service Fee', $surcharge, true, 'standard' );
}
但再一次,这个解决方案存在一些问题......
1) 不考虑产品类别 2)它会根据整个购物车价值添加费用,但它应该只对“门票”产品类别中的产品添加 5% 的费用,而不是整个购物车
【问题讨论】:
标签: php wordpress woocommerce