I need to apply a discount to the cart subtotal before tax is calculated if a user is ordering for the first time. However, tax is calculated per-item in WooCommerce and added to the subtotal afterwards.
So I need to apply the discount to the items in the cart before WooCommerce calculates the tax on them. This way the tax is based off of the discounted prices rather than the original prices.
Here is what I have:
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' );
This echos out the right numbers I need, but now I need to apply those prices to the cart. Right now the prices in the cart do not change.
How can I apply the new prices from this function's calculations to the cart?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…