Search code examples
phpwordpresswoocommercecarthook-woocommerce

Disable "cart needs payment" for a specific coupon code in Woocommerce


I need to hide the payment by credit card when I have a specific coupon such as "tcrfam" and when I use any different to this show the payment by card, the idea is that I do not give a coupon of 100% or free and there is no case I ask credit card data.

See the example: I need

I tried this code but dont work:

add_action('woocommerce_before_checkout_form', 'apply_product_on_coupon');
function apply_product_on_coupon() {
  global $woocommerce;
  $coupon_id = 'tcrfam';
  if(in_array($coupon_id, $woocommerce->cart->get_applied_coupons())){    
    echo "Yes the coupon its inserted dd";
    add_filter( 'woocommerce_cart_needs_payment', '__return_false' );
  }
}

I need to use add_filter ('woocommerce cart needs payment', '__return_false'); within the function as in the code above but I don't know how to do it, can someone give me an idea of how to do it? Thank you


Solution

  • The code that you needs should be in the filter hook directly, like:

    add_filter( 'woocommerce_cart_needs_payment', 'filter_cart_needs_payment', 10, 2 );
    function filter_cart_needs_payment( $needs_payment, $cart  ) {
        // The targeted coupon code
        $targeted_coupon_code = 'tcrfam';
    
        if( in_array( $targeted_coupon_code, $cart->get_applied_coupons() ) ) {
            $needs_payment = false;
        }
        return  $needs_payment;
    }
    

    Code goes in functions.php file of your active child theme (or active theme). It should works.