Site icon Qaisar Satti's Blogs

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:

Exit mobile version