How to Automatically Apply a Discount Coupon to the Cart in WooCommerce

If you’re looking to add a discount programmatically to the cart without requiring the user to manually enter the coupon code, you’ll need to add custom code to your WooCommerce theme.

In this tutorial, I’ll show you how to automatically apply a discount coupon on the WooCommerce cart page using a simple PHP function.

 

// Automatically Apply Discount Coupon to the Cart in WooCommerce
 
function ts_apply_discount_to_cart() {
    $order_total = WC()->cart->get_subtotal(); // Get the cart subtotal

    // Check if the order total is greater than $100
    if( $order_total > 100 ) {
        $coupon_code = '10OFF'; // Your coupon code

        // Apply the coupon if it hasn't been applied already
        if ( ! WC()->cart->has_discount( $coupon_code ) ) {
            WC()->cart->apply_coupon( sanitize_text_field( $coupon_code ) );
        }
    }
}

// Hook the function to the cart page
add_action( 'woocommerce_before_cart_table', 'ts_apply_discount_to_cart' );

 

Working of Code:

  • The ts_apply_discount_to_cart() function is created to handle the automatic application of the coupon.
  • We use WC()->cart->get_subtotal() to get the total amount in the cart.
  • WC()->cart->apply_coupon() is used to apply the coupon.
  • We also check if the coupon hasn’t already been applied using ! WC()->cart->has_discount().
  • add_action( ‘woocommerce_before_cart_table’, ts_apply_discount_to_cart‘ ); attaches our function to the cart page, ensuring the discount is applied when the cart loads.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!