I am trying to pass the total amount of the cart ($GetTotalPrice
) from function cart_prices_GetPrice()
to function cart_prices_ApplyPrice()
, using a woocommerce_after_calculate_totals
and woocommerce_before_calculate_totals
hooks, but I get an empty value.
//Trying to get cart amount
add_action('woocommerce_after_calculate_totals', 'cart_prices_GetPrice');
function cart_prices_GetPrice() {
//Getting the cart amount
$GetTotalPrice = WC()->cart->get_cart_total();
return $GetTotalPrice;
}
//Applying custom price
add_action('woocommerce_before_calculate_totals', 'cart_prices_ApplyPrice');
function cart_prices_ApplyPrice( $cart_object ) {
//Getting the cart amount from first function
$totalprice = cart_prices_GetPrice(); // doesn't work and returns 0 :(
//price change to cost2
if( $totalprice != 0 && $totalprice >= 2000 ) {
foreach ( $cart_object->get_cart() as $cart_id => $cart_item ) {
// get products id
$product_id = $cart_item['product_id'];
if( $cart_item['product_id'] == $product_id ) {
// price change to cost2
$new_price1 = 0.20;
$cart_item['data']->set_price( $new_price1 );
}
}
}
}
At the same time, each of the functions separately works perfectly.
What am I doing wrong? Is it possible to somehow link two hook data so that the first one doesn't return an empty value?
Update:
I will not be able to refuse the hook woocommerce_before_calculate_totals
, because I need to apply a separate price reduction for each product in the cart.