[ad_1]
I am a PHP noob. I’m helping my friend set up a WooCommerce shop. He sells digital products. His pricing plan is as follows:
-buy the first copy of a product for full price (10€)
-buy all other copies for a discounted price (1€)
So, when a customer adds a product to their shopping cart, the first copy is full price. The prices of any additional copies of said product are added to the cart with discounted prices.
According to the pricing plan above, if a customer has two copies of a product in their cart, the total cart price should be 11€.
I’ve cobbled together this code:
add_action('woocommerce_before_calculate_totals', 'change_cart_price', 9999);
function change_cart_price($price_html) {
foreach( WC()->cart->get_cart() as $cart_item ){
//get the quantity of each separate product in the cart
$quantity = $cart_item['quantity'];
//if the quantity of an item is higher than one,
//decrease the for loop iterations by one
if ($quantity > 1) {
$iterations = $quantity -1;
//change the prices of all but one copy of the product
for ($i = 0; $i < $iterations; $i++) {
$price = $cart_item['data']->get_price();
$cart_item['data']->set_price(1);
}
}
}
return $price_html;
}
This code fires when the amount of a product in the cart is above one, but it changes the prices of all copies of the product. So, the cart total for two copies of a single product is 2€, instead of 11€.
Obviously, my “for” loop sucks. I’ve Googled different resources, but they tend to focus on changing the price of all the items in the cart.
I’ve thought about using an array that contains all the products. Maybe if I run through it and change prices according to Product ID?
Any help would be appreciated. Cheers.
[ad_2]