Add a discount for specific selected payment method in WooCommerce
Asked Answered
S

2

5

Without a using coupon functionality I would like to apply a 15% discount for a specific payment method ID like 'xyz'.

I would like help identifying which hooks to use. The general idea of what I would like to achieve is:

if payment_method_hook == 'xyz'{
    cart_subtotal = cart_subtotal - 15%
}

The customer does not need to see the discount on this page. I would like the discount to be submitted properly, only for the specific payment method.

Sweated answered 23/12, 2017 at 21:12 Comment(0)
H
10

You can use this custom function hooked in woocommerce_cart_calculate_fees action hook, that will make a discount of 15% for a defined payment method.

You should need to set in this function your real payment method ID (like 'bacs', 'cod', 'cheque' or 'paypal').

The 2nd function will refresh checkout data each time that a payment method is selected.

The code:

add_action( 'woocommerce_cart_calculate_fees','shipping_method_discount', 20, 1 );
function shipping_method_discount( $cart_object ) {

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

    // HERE Define your targeted shipping method ID
    $payment_method = 'bacs';

    // The percent to apply
    $percent = 15; // 15%

    $cart_total = $cart_object->subtotal_ex_tax;
    $chosen_payment_method = WC()->session->get('chosen_payment_method');

    if( $payment_method == $chosen_payment_method ){
        $label_text = __( "Shipping discount 15%" );
        // Calculation
        $discount = number_format(($cart_total / 100) * $percent, 2);
        // Add the discount
        $cart_object->add_fee( $label_text, -$discount, false );
    }
}

add_action( 'woocommerce_review_order_before_payment', 'refresh_payment_methods' );
function refresh_payment_methods(){
    // jQuery code
    ?>
    <script type="text/javascript">
        (function($){
            $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
    <?php
}

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

Tested and works.

Hem answered 23/12, 2017 at 22:8 Comment(2)
Beautiful, exactly what I was seeking. Thank you Loic!Sweated
But How can we limit the amount we are providing, I have used this condition but still I get more than 200 discount sometimes, ``` if($discount > 200){ $cart_object->add_fee( $label_text, -200, false ); }else{ $cart_object->add_fee( $label_text, -$discount, false ); } ```Hobard
D
1

This may help others.. I needed to check the payment method for 2 methods AND check if the user was a specific role..

if (($chosen_payment_method == 'stripe' || $chosen_payment_method == 'paypal') && current_user_can('dealer')) {
Diarist answered 17/4, 2019 at 21:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.