Sometimes we need to implement coupons that automatically apply themselves based on what’s in the cart, frequently as part of some sort of discount. Below is a snippet of commented code that I used to automatically apply a coupon based on two factors:

  • A quantity of a specific product is in the cart
  • The current date is BEFORE the end date for a sale.
//These actions run before the checkout form and the cart.
//The below actions will take place before either page is rendered,
//seamlessly applying (or removing) coupons before the user can see
add_action( 'woocommerce_before_checkout_form', 'holidaySpecial', 5 );
add_action( 'woocommerce_before_cart', 'holidaySpecial', 20, 1);

function holidaySpecial(){
  //If the current date is NOT earlier than the end time, do nothing.
  if (!checkHolidaySpecialTime()){
    return;
  }

  //Coupon Slug
  $couponName = 'holiday_2018';
  //Removes the coupon from the cart, just in case.
  WC()->cart->remove_coupon($couponName);

  //Goes through all cart items
  foreach(WC()->cart->get_cart() as $key => $product){
    //Checks if the product ID and quantity match a specific set of quantities
    if ($product['product_id'] == 461 && $product['quantity'] >= 2){
      //Applies the coupon code if the above quantities match
      WC()->cart->apply_coupon($couponName);
    }
  }
}

add_filter( 'woocommerce_coupon_is_valid', 'checkHolidayCoupon', 10, 2);

function checkHolidayCoupon($condition, $coupon){
  //Coupon Slug
  $couponName = 'holiday_2018';

  //Checking ONLY for the above referenced coupon
  if ($coupon -> get_code() == $couponName){

    if ( !checkHolidaySpecialTime() ){
      return false;
    }

    //Goes through all products in the cart
    foreach(WC()->cart->get_cart() as $key => $product){
      //If the product meets very specific parameters, return true, end function
      if ($product['product_id'] == 461 && $product['quantity'] >= 2){
        return true;
      }
    }
    //If the loop is finished and we haven't returned true yet, return false.
    //Products in cart don't match the specified parameters
    return false;
  }

  //If the coupon code doesn't match the holiday coupon,
  //return $condition, move on.
  return $condition;
}

function checkHolidaySpecialTime(){
  //Set the current timezone to the nearest locale
  date_default_timezone_set('America/Chicago');

  //Set the end time for the discount.
  //This discount ends at the end of December 31, 2018
  if (time() < strtotime("01/01/19 00:00:00")){
    return true;
  } else {
    return false;
  }
}