title: How do I programmatically apply a coupon in Woocommerce automatically?
body: <p>Hi I'm looking to automatically apply a coupon discount of 20% to the cart when its total is €25 or more - I've looked at the code from a previous user and tried modifying it and placing it in the functions.php, however it doesn't work for me - Any help as to what I'm doing wrong/?   Here is the code I placed into functions.php;</p>
  
  <pre><code>/* Mod: 20% Discount for orders over €25 
  Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $subtotal of cart:
          global $subtotal;
          $subtotal= $woocommerce-&gt;cart-&gt;subtotal;
  */
  add_action('woocommerce_before_cart_table', 'discount_when_order_greater_25');
  function discount_when_order_greater_25( ) {
      global $woocommerce;
      global $subtotal;
      if( $subtotal &gt;= 25 ) {
          $coupon_code = '20';
          if (!$woocommerce-&gt;cart-&gt;add_discount( sanitize_text_field( $coupon_code ))) {
              $woocommerce-&gt;show_messages();
          }
          echo '&lt;div class="woocommerce_message"&gt;&lt;strong&gt;Your order is over €25 so a 20% Discount has been Applied!&lt;/strong&gt; Your total order weight is &lt;strong&gt;' . $total_weight . '&lt;/strong&gt; lbs.&lt;/div&gt;';
      }
  }
  
  /* Mod: 20% Discount for orders under €25  */
  add_action('woocommerce_before_cart_table', 'remove_discount_when_order_less_25');
  function remove_discount_when_order_less_25( ) {
      global $woocommerce;
      global $subtotal;
      if( $subtotal &lt; 25 ) {
          $coupon_code = '20';
          $woocommerce-&gt;cart-&gt;get_applied_coupons();
          if (!$woocommerce-&gt;cart-&gt;remove_coupons( sanitize_text_field( $coupon_code ))) {
              $woocommerce-&gt;show_messages();
          }
          $woocommerce-&gt;cart-&gt;calculate_totals();
      }
  }
  </code></pre>