我一直在寻找一种方法在Woocommerce网站上的TOTAL Cart Amount上添加存款(而不是仅为每个产品系列项目添加存款)。
我在这里找到了这个巧妙线索的答案: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,我可以在前端设置描述样式。)
但是,我有一些产品(一种产品类别),我不想强迫这笔存款。
所以,这是我的问题:
如何调整代码以继续强制执行默认存款,但从一个产品类别中排除存款(如果我不能排除整个类别,则排除此类别中的产品)?
答案 0 :(得分:0)
在下面的钩子函数中,您必须设置一组产品ID或(和)产品类别,以排除它们。如果您不使用其中一个,则可以设置一个空白数组,例如$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上测试并正常工作。