爲WooCommerce每個產品添加費用我一直在嘗試一段時間才能使此工作正常,但是我還沒有找到任何解決方案來滿足我們的需求,而且我遠離專家在PHP中,所以我有點失落。根據類別
我們使用WooCommerce和WooTickets。目標是將「服務費」的5%費用僅限於「門票」類別(ID:34)中的產品。
我們發現這段代碼剪斷,即添加基於產品類別的固定成本:
// 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自己:
/**
* 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%的費用,而不是整個購物車
非常感謝您的回答@Bartoszkp/@Sartorius! 將邏輯推得更遠,您將如何根據數量動態更改費用?例如,如果票少於10張,票價爲5%,如果票數爲11至20票,票價爲2.5%,如果票數超過20張,則收取全額費用? 將類似的東西工作: '如果($ specialfeecat == $ CATID){ 如果($量<= '10'){$ spfee = $ spfee + $ itmprice * $ quantiy *($ spfeeperprod/2);} }' 再次感謝您的幫助! – thisisbbc 2014-11-25 21:29:58