默认存款占总购物车金额的百分比,但有例外
问题描述:
我正在寻找一种方法在Woocommerce网站上的总购物车金额上添加存款(而不是仅向每个产品订单项添加存款)。默认存款占总购物车金额的百分比,但有例外
我找到了答案,这种巧妙的线程在这里:Deposit based on a percentage of total cart amount
这是我最后的代码中使用:
add_action('woocommerce_cart_calculate_fees', 'booking_deposit_calculation');
function booking_deposit_calculation($cart_object) {
if (is_admin() && ! defined('DOING_AJAX'))
return;
## Set HERE your negative percentage (to remove an amount from cart total)
$percent = -.50; // 50% off (negative)
// Get cart subtotal excluding taxes
$cart_subtotal = $cart_object->subtotal_ex_tax;
// or for subtotal including taxes use instead:
// $cart_subtotal = $cart_object->subtotal;
## ## CALCULATION ## ##
$calculated_amount = $cart_subtotal * $percent;
// Adding a negative fee to cart amount (excluding taxes)
$cart_object->add_fee(__('Deposit calculation', 'woocommerce'), $calculated_amount, false);
}
这造成50%的定金为对车和结算的每个产品默认页。辉煌! (使用CSS,然后我可以在前端描述样式)。
但是,我有几个产品(一个产品类别),我不想强制使用此存款。
所以,这里是我的问题:
我如何调整代码继续执行默认的存款,但不包括从一个产品类别的存款(或产品这一类,如果我不能排除整个类别)?
答
在下面的挂钩函数中,您将不得不设置产品类别的数组,然后将其排除。如果你不使用其中之一,你可以设置一个空白阵列例如像$product_categories = array();
...
下面是代码:
add_action('woocommerce_cart_calculate_fees', 'custom_deposit_calculation', 10, 1);
function custom_deposit_calculation($cart_object) {
if (is_admin() && ! defined('DOING_AJAX'))
return;
// Define the product IDs to exclude
$product_ids = array(37, 25, 50);
// Define the product categories to exclude (can be IDs, slugs or names)
$product_categories = array('clothing');
$amount_to_exclude_with_tax = 0;
// Iterating through cart items
foreach ($cart_object->get_cart() as $cart_item){
// If condition match we get the sum of the line item total (excl. tax)
if(in_array($cart_item['product_id'], $product_ids) || has_term($product_categories, 'product_cat', $cart_item['product_id']))
$amount_to_exclude_with_tax += $cart_item['line_total'];
// OR replace by (for tax inclusion)
// $amount_to_exclude_with_tax += $cart_item['line_tax'] + $cart_item['line_total'];
}
## Set HERE your negative percentage (to remove an amount from cart total)
$percent = -0.5; // 50% off (negative)
// Get cart subtotal excluding taxes
$cart_subtotal = $cart_object->subtotal_ex_tax - $amount_to_exclude_with_tax;
// or for subtotal including taxes use instead:
// $cart_subtotal = $cart_object->subtotal;
## ## CALCULATION ## ##
$calculated_amount = $cart_subtotal * $percent;
if($calculated_amount != 0){
// Adding a negative fee to cart amount (Including taxes)
$cart_object->add_fee(__('Deposit calculation', 'woocommerce'), $calculated_amount, true);
}
}
代码放在您的活动子主题的function.php文件(或主题)或任何插件文件。
在WooCommerce 3上测试并工作。