Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change price of product in WooCommerce cart and checkout

I'm creating a WooCommerce add-on to customize the product, based on selected options by the visitor and custom price is calculated and stored into session table also.
I am able to get that value in cart page also.

My problem:
I would like to change the default price of the product and replace it with new calculated value in the WooCommerce process as cart, checkout, payment, mail notifications, order...

Any advice please?

Thanks

like image 969
Thilip Kumar Avatar asked Jul 07 '17 15:07

Thilip Kumar


1 Answers

Ce right hook to get it working is woocommerce_before_calculate_totals. But you will have to complete (replace) the code to get the new price in the hooked function below:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

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

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

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get the product id (or the variation id)
        $product_id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        $new_price = 500; // <== Add your code HERE

        // Updated cart item price
        $cart_item['data']->set_price( $new_price ); 
    }
}

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

This code is tested and works on WooCommerce versions 3+. But as you don't give any code I can't test it for real getting the new price from session…

like image 109
LoicTheAztec Avatar answered Sep 30 '22 18:09

LoicTheAztec