Updating cart subtotal in WooCommerce

15,685

You are using the right hook and here is the functional and tested code for Woocommerce version 2.6x to 3.0+, that is going to do the trick (instead you can make your calculation on cart items, and you will get the same thing) :

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart_object->get_cart() as $cart_item ) {
        ## Price calculation ##
        $price = $cart_item['data']->price * 12;

        ## Set the price with WooCommerce compatibility ##
        if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
            $cart_item['data']->price = $price; // Before WC 3.0
        } else {
            $cart_item['data']->set_price( $price ); // WC 3.0+
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


Explanations:

Using a calculation based on the cart subtotal, will only display the calculation on subtotal cart line row, without updating the cart items, the cart items line subtotals, and the cart total.

You can see it trying this working code for WooCommerce version 2.6.x and 3.0+:

add_action( 'woocommerce_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )
        return;

    $cart_object->subtotal *= 12;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Share:
15,685
Ravi Varma
Author by

Ravi Varma

Updated on June 13, 2022

Comments

  • Ravi Varma
    Ravi Varma over 1 year

    I want to update cart subtotal in WooCommerce.

    How can add action for modifying subtotal in WooCommerce?

    I have tried to by this code, but is not working. I would like to multiply by 12 the cart subtotal and to display this calculation on cart page.

    Here is my code:

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    function add_custom_price( $total) {
    
        foreach ( $total->cart_contents as $key => $value ) {
    
            $modifiedtotal = $total->subtotal * 12; 
            // --------------------------------
            //how can get subtotal with multiply by 12 and it should be show on cart page.
        }
    }