I'm using woocommerce_before_calculate_totals for updating product price to 0 (using set_price) and it's works great but I can't know what is the cart discount amount (coupons), I have to know that because I want to change the price only if the total price of the cart is 100$ or more (after the coupons discount).
When I'm using woocommerce_after_calculate_totals I able to know the cart discount amount but I can't change the product price.
I realize that when I'm using both it's working but I wonder if there is a better way to do that.
function check_gift_status() {
$gift_products = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'fields' => 'ids',
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => 405,
)
),
) );
$all_gift_products_ids = $gift_products->posts;
$gift_product_price_limit = 100;
$total = 0;
foreach ( WC()->cart->cart_contents as $key => $item ) {
$current_product_id = $item['product_id'];
if(in_array($current_product_id, $all_gift_products_ids)) continue;
$total += (float)$item['line_subtotal'];
}
$discount_excl_tax_total = WC()->cart->get_cart_discount_total();
$discount_tax_total = WC()->cart->get_cart_discount_tax_total();
$discount_total = $discount_excl_tax_total + $discount_tax_total;
$total -= $discount_total;
return ($total >= $gift_product_price_limit);
}
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_price', 10, 1 );
add_action( 'woocommerce_after_calculate_totals', 'conditionally_change_cart_items_price', 10, 1 );
function conditionally_change_cart_items_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$gift_products = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'fields' => 'ids',
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => 405,
)
),
) );
$all_gift_products_ids = $gift_products->posts;
if(check_gift_status()) {
foreach ( $cart_object->get_cart() as $key => $val ) {
$current_product = $val['data'];
if(in_array($current_product->id, $all_gift_products_ids)) {
$current_product->set_price( 0 );
}
}
}
}