Ad
Force Coupon Code Before Checkout In WooCommerce
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad