I would like to change the product prices. This is what I have tried:
function regular_price_func($price, $product) {
if (!empty(get_field("zusatzlicher_rabatt", 'options')['rabatt_status']) && is_product($product->get_id())) {
$discount_in_procent = (($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100;
if ($discount_in_procent > 49) {
return ($product->get_regular_price() - ($product->get_regular_price() / 100) * ($discount_in_procent + get_field("zusatzlicher_rabatt", 'options')['produkte_uber_50']));
}
else {
return ($product->get_regular_price() - ($product->get_regular_price() / 100) * ($discount_in_procent + get_field("zusatzlicher_rabatt", 'options')['produkte_unter_50']));
}
}
return $price;
}
add_filter('woocommerce_product_get_price', 'regular_price_func', 10, 2);
This will change the price on the product page, but when adding that item to the cart, the cart page still displays the official price, so my function has no effect.
To achieve my goal, I have tried it this way:
function custom_change_product_price($cart_object) {
foreach ($cart_object->get_cart() as $cart_item_key => $cart_item) {
$new_price = 100;
$cart_item['data']->set_price($new_price);
}
}
add_action('woocommerce_before_calculate_totals', 'custom_change_product_price');
This will change the price to 100. However, I want the price, which I have defined in the function regular_price_func. How do I do this?
Something like this:
$cart_item['data']should be an instance of the WC_Product class.I seen the other answer that was deleted after I posted this, which is basically the same ( maybe a bit messier ). I'm not one to steal credit, so when you said "It's not working". You should make sure your pricing logic works correctly. There is some conditions in there and some custom options that need to be set. It's far more likely there is an additional issue there. If none of those conditions pass then it's just going to return the products original price. That doesn't mean there is anything wrong with the above code, or the other answer.
Your not asking us to validate the logic of that function, which would be impossible, there is stuff ( data ) we just don't have to do that.
I voted to undelete the other answer, that's the most I can do.
One last thing I can add, if you type hint this ( I capitalize objects ):
You wont have to check
is_product($Product->get_id())because it has no choice but to be a product.