PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] How to get discount amount to set cart item prices to zero in WooCommerce before calculating totals

 February 05, 2022     hook-woocommerce, woocommerce, wordpress     No comments   

Issue

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 );
            }
        }
    }
}

Solution

You can get cart totals from the current customer session (WC_Session).

Inside the hook woocommerce_before_calculate_totals use WC()->session->get('cart_totals'); to get cart totals.

You can also check if a product belongs to a specific product category or not via the Wordpress has_term function.

In your code, you are subtracting both the discount tax and the discount amount. If the products are priced excluding taxes, perhaps you should only subtract the discount amount.

The optimized function is:

// Set cart item prices to zero based on cart total.
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_price', 99, 1 );
function conditionally_change_cart_items_price( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    // Defines the gift product category id.
    $gift_product_cat_id       = 405;

    // Set the threshold for applying prices to zero.
    $gift_product_price_limit  = 100;

    // Gets the total cart discount from the current customer session.
    $cart_totals               = WC()->session->get('cart_totals');
    $total_discount            = $cart_totals['discount_total'] + $cart_totals['discount_tax'];
    
    // Calculates the sum of the cart item prices that do not belong to the gift product category.
    $total = 0;
    foreach ( $cart->get_cart() as $cart_item ) {
        if ( ! has_term( $gift_product_cat_id, 'product_cat', $cart_item['product_id'] ) ) {
            $total += (float) $cart_item['line_subtotal'];
        }
    }

    // If the product subtotal (including discounts) is greater than or equal to the threshold, set the gift item prices to zero.
    if ( ( $total - $total_discount ) >= $gift_product_price_limit ) {
        foreach ( $cart->get_cart() as $cart_item ) {
            if ( has_term( $gift_product_cat_id, 'product_cat', $cart_item['product_id'] ) ) {
                $cart_item['data']->set_price( 0 );
            }
        }
    }

}

The code has been tested and works. Add it to your active theme's functions.php.



Answered By - Vincenzo Di Gaetano
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing