Are there times when we need to apply coupon programmatically to Cart and Checkout without manual insertion.

There are two action hooks we can utilize:

  • woocommerce_before_cart – The hook that runs before the Shopping Cart on Cart page
  • woocommerce_checkout_update_order_review – The action hook that gets called every time the checkout is updated (e.g. when you changed billing or shipping address)

Add this block of codes into your functions.php. (Remember to change the coupon code and add your own conditions where necessary.)

Add action to woocommerce_before_cart & woocommerce_checkout_update_order_review

add_action( 'woocommerce_before_cart', 'cart_autoapply_coupon_first_order' );
add_action( 'woocommerce_checkout_update_order_review', 'cart_autoapply_coupon_first_order' );
function cart_autoapply_coupon_first_order() {
	$coupon_code = 'couponabc123';
	if ( WC()->cart->has_discount( $coupon_code ) ) {
		// Cart contains this coupon code. do nothing
	} else {
		WC()->cart->apply_coupon( $coupon_code );