jord49
jord49

Reputation: 582

Add total discount coupons amount in Woocommerce checkout

I am trying to add up all of my added coupons to get a discount total in the checkout. I tried adding a variable at the top of the checkout template file and doing ++ for each entry but I throws errors.

Any ideas how to add the values to a variable to get a total?

The checkout totals regenerate if you alter a value so I found my answer being outputted each time the loop runs.

My code:

<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
        <tr class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
            <th><?php wc_cart_totals_coupon_label( $coupon ); ?></th>
            <td><?php $helloworld = wc_cart_totals_coupon_html( $coupon )++; ?></td>
        </tr>
    <?php endforeach; ?>

Upvotes: 3

Views: 4766

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

This can be done easily using some existing WC_Cart methods.

So in the template checkout/oreder-review.php, just after this:

        <?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
            <tr class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                <th><?php wc_cart_totals_coupon_label( $coupon ); ?></th>
                <td><?php wc_cart_totals_coupon_html( $coupon ); ?></td>
            </tr>
        <?php endforeach; ?>

You will insert the following code (after line 69):

        <?php
            $discount_excl_tax_total = WC()->cart->get_cart_discount_total();
            $discount_tax_total = WC()->cart->get_cart_discount_tax_total();
            $discount_total = $discount_excl_tax_total + $discount_tax_total;
        if( ! empty($discount_total) ): ?>
            <tr class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                <th><?php _e('Discount total','woocommerce'); ?></th>
                <td><?php echo wc_price(-$discount_total) ?></td>
            </tr>
        <?php endif; ?>

Tested and works.

enter image description here

Upvotes: 3

Related Questions