title: Applying conditionally a generated coupon on WooCommerce add to cart
body: <p>I'm currently using Gravity Forms (with referral as lead enabled). I'm using a hook on submit to generate a random coupon based off of a coupon template (in my functions.php). My goal is to then have that coupon automatically applied to their order at the checkout page. I'm successfully able to generate the coupon, but can't quite figure out how to apply it. FYI- I do not use a cart in the user experience, so Product Page &gt; Checkout.</p>
  <p>If someone could provide some help, or point me in the right direction, I'd be grateful.</p>
  <pre><code>// Generate Random Coupon  
  function after_submission () {
  $coupon_code = substr( &quot;abcdefghijklmnopqrstuvwxyz123456789&quot;, mt_rand(0, 50) , 1) .substr( md5( time() ), 1); // Code
  $coupon_code = substr( $coupon_code, 0,10); // create 10 letters coupon
  $amount = '0'; // Amount
  $discount_type = 'free_shipping'; // Type: fixed_cart, percent, fixed_product, percent_product
  
  $coupon = array(
      'post_title' =&gt; $coupon_code,
      'post_content' =&gt; 'Free Shipping &amp; Handling',
      'post_excerpt' =&gt; 'Free Shipping &amp; Handling',
      'post_status' =&gt; 'publish',
      'post_author' =&gt; 1,
      'post_type'     =&gt; 'shop_coupon'
  );
  
  $new_coupon_id = wp_insert_post( $coupon );
  
  // Add meta
  update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
  update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
  update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
  update_post_meta( $new_coupon_id, 'product_ids', '' );
  update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
  update_post_meta( $new_coupon_id, 'usage_limit', '1' );
  update_post_meta( $new_coupon_id, 'expiry_date', '' );
  update_post_meta( $new_coupon_id, 'apply_before_tax', 'no' );
  update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
  update_post_meta( $new_coupon_id, 'exclude_sale_items', 'no' );
  update_post_meta( $new_coupon_id, 'free_shipping', 'yes' );
  update_post_meta( $new_coupon_id, 'product_categories', '' );
  update_post_meta( $new_coupon_id, 'exclude_product_categories', '' );
  update_post_meta( $new_coupon_id, 'minimum_amount', '' );
  update_post_meta( $new_coupon_id, 'customer_email', '' );       
  
  return $coupon_code;
  
  }
  
  // Gravity Forms Referral 
  add_action( 'gform_after_submission_9', 'after_submission', 10, 2 );
  
  
  // Add generated coupon to cart 
  add_action( 'woocommerce_add_to_cart', 'apply_matched_coupons' );
  
  function apply_matched_coupons() {
       if ( is_cart() || is_checkout() ) return;
       if ( WC()-&gt;cart-&gt;has_discount( $coupon_code ) ) return;
       WC()-&gt;checkout-&gt;add_discount( $coupon_code );
  }
  </code></pre>