woocommercecartcheckoutcoupon

Conditional coupon error messages on WooCommerce


I am trying to build a WooCommerce checkout page with an open coupon form by disabling the toggle. I modified the code given in here by adding the following to it so it removes the big blue notification message too.

$(".showcoupon").closest(".woocommerce-info").hide();  

Only issue is if someone clicks the Apply Coupon with an empty or incorrect coupon code, it displays the error and hides the coupon code field. Therefore I added the below so it gives the user another chance to get the coupon form.

add_filter( 'woocommerce_coupon_error', 'pm_change_coupon_error', 30, 3 );

function pm_change_coupon_error( $err, $err_code, $coupon ){

if (is_checkout()) {        
    $err =  ' <a class="showcoupon">' . __( 'Click here to enter a valid coupon code', 'woocommerce' ) . '</a>';    
}
else {
    $err  =  'Please enter a valid code'; //Error message for cart page
}
return $err;
}

No matter what modifications I tried, it always displays the error message given for the else statement. How can I make sure there will always be 2 separate messages depending on the page?


Solution

  • I ended up using a CSS based solution by adding the following:

    .woocommerce-checkout .checkout_coupon.woocommerce-form-coupon { display:block !important; }
    

    Optionally to disable the "Have a coupon? Click here to enter your code" message, added the following:

    .woocommerce-form-coupon-toggle .woocommerce-info {display: none !important;}
    

    Coupon fields and the error message 'jump' a bit when a customer is logged in. Other than that it works fine.