Auto Apply Coupon

Automatically applies a predefined coupon code to the cart.

PHP
/**
 * Snippet Name:     Auto Apply Coupon
 * Snippet Author:   coding-bunny.com
 * Description:      Automatically applies a predefined coupon code to the cart.
 * Version:          1.1.0
 */

define('COUPON_AUTO_APPLY_CODE', 'YOUR_COUPON_NAME_HERE');

function cbacd_apply_coupon_automatically() {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( ! WC()->cart ) return;

    $coupon = new WC_Coupon( COUPON_AUTO_APPLY_CODE );
    if ( ! $coupon->get_id() || ! $coupon->is_valid() ) {
        return;
    }

    if ( ! WC()->cart->has_discount( COUPON_AUTO_APPLY_CODE ) ) {
        WC()->cart->apply_coupon( COUPON_AUTO_APPLY_CODE );
    }
}
add_action( 'woocommerce_before_calculate_totals', 'cbacd_apply_coupon_automatically', 10 );

How To Implement This Solution?

Leave a Reply