如果用户第一次订购,我需要在计算税额之前对购物车小计应用折扣 . 但是,税收是在WooCommerce中按项目计算的,之后会添加到小计中 . 所以我需要在WooCommerce计算税收之前将折扣应用到购物车中的商品 . 这种方式的税收是基于折扣价而不是原价 .
这是我有的:
function first_order_add_five_percent_discount($cart_object) {
if ( is_user_logged_in() ) {
//current user id
$currentUser_id = get_current_user_id();
//amount of orders by current user
$orderAmount = wc_get_customer_order_count( $currentUser_id );
//if user has 0 orders...
if ($orderAmount == 0) {
//for each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {
//$item_id = $item_values['data']->id; // Product ID
$item_qty = $item_values['quantity']; // Item quantity
$original_price = $item_values['data']->price; // Product original price
echo $original_price . "<br>";
$totalPrice = $original_price * $item_qty;
$discountedPrice = $totalPrice * .05;
$newPrice = $original_price - $discountedPrice;
echo $totalPrice . "<br>";
echo $discountedPrice . "<br>";
echo $newPrice . "<br>";
$item_values['data']->set_price($newPrice);
}
} else {
//do nothing
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'first_order_add_five_percent_discount' );
这回应了我需要的正确数字,但现在我需要将这些价格应用到购物车中 . 现在购物车中的价格不会改变 .
如何将此功能计算的新价格应用到购物车?
1 回答
有一种更为简单的方法,就是使用负费, so a discount . 它使用
WC_Cart
方法add_fee()
where you can disable tax :代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中 .
经过测试和工作 . 你会得到类似的东西:
如您所见,折扣是购物车内容总额的佣人 . 税