5

With woocommerce, in my website I'd like to add in the cart page a select input where the user can select a value between two options, and depending on this value I will change the price.

so far, I could get the total and change it using this :

function action_woocommerce_before_cart_totals(  ) { 
 global $woocommerce;

 $woocommerce->cart->total  = $woocommerce->cart->total*0.25;
   var_dump( $woocommerce->cart->total);}; 

The issue is that when I go to checkout page it doesn't take the total calculated in functions.php

Thanks for helping me.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Hanane
  • 345
  • 1
  • 8
  • 19

2 Answers2

9

You can use woocommerce_review_order_before_order_total hook too at the same time, to display your custom price in checkout, this way:

add_action( 'woocommerce_review_order_before_order_total', 'custom_cart_total' );
add_action( 'woocommerce_before_cart_totals', 'custom_cart_total' );
function custom_cart_total() {

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

    WC()->cart->total *= 0.25;
    //var_dump( WC()->cart->total);
}

The 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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • yes it works perfectly but when I choose one of the payment method it doesn't take the total calculated in functions.php. Thanks a lot I will search for a solution for that. Thanks again. – Hanane Apr 08 '17 at 09:00
  • 1
    @LoicTheAztec Nice stuff can we make a button and update the price with ajax using: jQuery(document.body).trigger("update_checkout"); – mysticalghoul Oct 12 '17 at 15:58
0

Payment gateway always uses $order->get_total() variable to fetch cart grand total. So in order to tweak use this filter woocommerce_order_amount_total for your function if you do follow below steps. Your payment gateway always shows the total you tweaked.

add_filter( 'woocommerce_order_amount_total', 'custom_cart_total' );
function custom_cart_total($order_total) {
  return $order_total *= 0.25;
}
Stepan Novikov
  • 1,402
  • 12
  • 22
Saminathan K
  • 19
  • 1
  • 9