Ad

Force Coupon Code Before Checkout In WooCommerce

- 1 answer

I want to force the customer to add a coupon code before they can go to checkout. I would like it to work with every coupon code and every product in my WooCommerce store.

I am using this code and it is almost solving the problem, but it only works on a single coupon code (freev1)

How is it possible to make it work on every coupon code generated?

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
    // HERE set your coupon code
    $mandatory_coupon = 'freev1';

    $applied_coupons = WC()->cart->get_applied_coupons();

    // If coupon is found we exit
    if( in_array( $mandatory_coupon, $applied_coupons ) ) return;

    // Not found: display an error notice
    wc_add_notice( __( 'Add coupon before checkout.', 'woocommerce' ), 'error' );
}
Ad

Answer

Just check if $applied_coupons is empty, when empty add notice. Remove $mandatory_coupon & if ( in_array...

So you get

function mandatory_coupon_code() {
    $applied_coupons = WC()->cart->get_applied_coupons();

    if ( empty ( $applied_coupons ) ) {
        // Not found: display an error notice
        wc_add_notice( __( 'Add coupon before checkout.', 'woocommerce' ), 'error' );   
    }
}
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code', 10, 0 );
Ad
source: stackoverflow.com
Ad