2
votes

I was trying to make a code snippet for functions.php which would apply a discount of 2 % for cart totals when the role "subscriber" and the payment method "credit-card" are both selected. My progress so far

function discount_when_role_and_payment(/* magic */) {
global $woocommerce;
if ( /* credit-card selected */ && current_user_can('subscriber') ) {
    /* get woocommerce cart totals, apply 2% discount and return*/
} 
return /*cart totals after discount*/;
}

add_filter( '/* magic */', 'discount_when_role_and_payment' );

Could anyone help complete this? Or atleast point to the right direction?

1

1 Answers

4
votes

The following code will apply a discount of 2% to cart when a targeted payment method has been selected by a subscriber user role only on checkout page:

// Applying conditionally a discount
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role_and_payment', 20, 1 );
function discount_based_on_user_role_and_payment( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    // Only on checkout page for 'subscriber' user role
    if ( ! ( is_checkout() && current_user_can('subscriber') ) )
        return; // Exit

    // HERE Below define in the array your targeted payment methods IDs
    $targeted_payment_methods = array( 'paypal', 'stripe' );
    // HERE define the percentage discount
    $percentage = 2;

    if( in_array( WC()->session->get('chosen_payment_method'), $targeted_payment_methods ) ){
        // Calculation
        $discount = $cart->get_subtotal() * $percentage / 100;
        // Applying discount
        $cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
    }
}

// Refreshing totals on choseen payment method change event
add_action( 'woocommerce_review_order_before_payment', 'refresh_payment_methods' );
function refresh_payment_methods(){
    // Only on checkout page
    if ( ! ( is_checkout() && current_user_can('subscriber') ) ) return;
    // jQuery code
    ?>
    <script type="text/javascript">
        (function($){
            $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
    <?php
}

This code goes on function.php file of your active child theme (or active theme). tested and works.

enter image description here

To get the correct desired Payment methods IDs, you will have to inspect the html code around the payment methods radio buttons searching with your browser inspector tools:

enter image description here