Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Change Cart total using Hooks in Woocommerce 3.2+

I want to add 300 to order total on woocommerce checkout page but woocommerce_calculate_totals hook doesn't do the job...

If I use var_dump($total), I see the correct result - int(number), but the total amount in order table is not changing.

add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );

function action_cart_calculate_totals( $cart_object) {

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

    if ( !WC()->cart->is_empty() ):


        $total = $cart_object->cart_contents_total += 300;

        var_dump($total);

    endif;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since Woocommerce 3.2, the hook woocommerce_calculate_totals doesn't work for that.
See explanations on this thread: Change Cart total price in WooCommerce

You will have to use one of the following ways using:

1) The filter hook woocommerce_calculated_total this way:

add_filter( 'woocommerce_calculated_total', 'change_calculated_total', 10, 2 );
function change_calculated_total( $total, $cart ) {
    return $total + 300;
}

2) The Fee API like:

add_action( 'woocommerce_cart_calculate_fees', 'add_custom_fee', 10, 1 );
function add_custom_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $fee = 300;

    $cart->add_fee( __( 'Fee', 'woocommerce' ) , $fee, false );
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...