Answer the question
In order to leave comments, you need to log in
How to correctly call the value of the product meta field in the cart?
I need to be able to substitute a different price for a certain amount of goods.
From 50 pieces so that the price is prescribed differently. I want to take the value of this new price from my added numeric meta field.
There is a snippet that does a very similar thing - changing the cost of a product from the required number of pieces, but with a percentage discount. Works great.
add_action( 'woocommerce_before_calculate_totals', 'phpsof_quantity_based_pricing', 9999 );
function phpsof_quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Define discount rules and thresholds
$threshold1 = 50; // Change price if items > 50
$discount1 = 0.05; // Reduce unit price by 5%
$threshold2 = 100; // Change price if items > 100
$discount2 = 0.1; // Reduce unit price by 10%
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount1), 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
$cart_item['data']->set_price( $price );
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question