Home Change Cart total price in WooCommerce
Reply: 2

Change Cart total price in WooCommerce

DEVPROCB
1#
DEVPROCB Published in 2017-04-14 16:49:46Z

I am running into issues with the cart total only displaying 0

Essentially what I am trying to do is only accept a deposit total of a certain amount after all cart items have been added to the carts subtotal.

So for example if the customer adds $100 worth of items, they would only pay $10 initially or (10%) of the subtotal as the total value.

I took the code from here: Change total and tax_total Woocommerce and customize it this way:

add_action('woocommerce_cart_total', 'calculate_totals', 10, 1);

function calculate_totals($wc_price){
$new_total = ($wc_price*0.10);

return wc_price($new_total);
} 

But the total amount shows 0.00 when that code is enabled. If removed the code, I get the standard total.

I also could not find on the woocommerce site where the full api is listed, only generic articles related to how to create a plugin.

Any help or a point in the right direction would be great.

LoicTheAztec
2#
LoicTheAztec Reply to 2017-04-15 14:26:44Z

First woocommerce_cart_total hook is a filter hook, not an action hook. Also as $wc_price argument in woocommerce_cart_total is the formatted price, you will not be able to increase it by 10%. That's why it returns zero.

WooCommerce Version 3.0+: Some WC_Cart properties can still be accessed directly

You should better use a custom function hooked in woocommerce_calculate_totals action hook
this way:

// Tested in WooCommerce versions 2.6.x and 3.0+
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() ):
        ## Displayed subtotal (+10%)
        // $cart_object->subtotal *= 1.1;

        ## Displayed TOTAL (+10%)
        // $cart_object->total *= 1.1;

        ## Displayed TOTAL CART CONTENT (+10%)
        $cart_object->cart_contents_total *= 1.1;

    endif;
}

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

Is also possible to use WC_cart add_fee() method in this hook, or use it separately like in Cristina answer.

Christina
3#
Christina Reply to 2017-04-14 18:29:53Z

This does not answer this question. Loic's does. This is another way of doing it to show a line item of 10% off:

function prefix_add_discount_line( $cart ) {

  $discount = $cart->subtotal * 0.1;

  $cart->add_fee( __( 'Down Payment', 'yourtext-domain' ) , -$discount );

}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' );

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304288 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO