Posted By

wyattstorch42 on 02/22/14


Tagged

wordpress product coupons addons woocommerce


Versions (?)

Customize WooCommerce Coupons for Product Add-Ons


 / Published in: PHP
 

This hackish solution was the only way I could find to make a WooCommerce coupon conditional to how the customer customized a product. Using the WooCommerce Add-Ons extension, which allows users to customize the product (e.g. shirt size/color), add this snippet to a plugin (or theme) to check a particular coupon code against some custom conditions based on what the user entered before deciding whether the coupon code applies.

  1. <?php
  2. if (!function_exists('my_plugin_woocommerce_coupon_is_valid_for_product')) {
  3. $my_product_counter = 0;
  4. define('MY_EXCEPTION_COUPON_CODE', 'XL-50-OFF');
  5. define('MY_EXCEPTION_ADDON_NAME', 'Shirt Size');
  6. define('MY_EXCEPTION_ADDON_VALUE', 'XL');
  7.  
  8. function my_plugin_woocommerce_coupon_is_valid_for_product (&$valid, $product, $coupon) {
  9. global $woocommerce, $my_product_counter;
  10.  
  11. if ($coupon->code != MY_EXCEPTION_COUPON_CODE) {
  12. return $valid;
  13. }
  14.  
  15. $cart = array_values($woocommerce->cart->get_cart());
  16. $item = $cart[$pbmi_product_counter];
  17.  
  18. if (isset($item['addons']) && is_array($item['addons'])) {
  19. foreach ($item['addons'] as $addon) {
  20. if ($addon['name'] == MY_EXCEPTION_ADDON_NAME && $addon['value'] == MY_EXCEPTION_ADDON_VALUE) {
  21. $valid = false;
  22. break;
  23. }
  24. }
  25. }
  26.  
  27. $my_product_counter = $my_product_counter < count($cart)-1 ? $my_product_counter+1 : 0;
  28.  
  29. return $valid;
  30. }
  31. add_filter('woocommerce_coupon_is_valid_for_product', 'my_plugin_woocommerce_coupon_is_valid_for_product', 9999, 3);
  32. }
  33. ?>

Report this snippet  

You need to login to post a comment.