In newer versions of WooCommerce, you will need to
- Register a custom coupon type
- Validate the coupon
- Calculate & Apply the discount
Register custom coupon type
add_filter( 'woocommerce_coupon_discount_types', 'custom_coupon_type',10, 1); function custom_coupon_type( $discount_types ) { $discount_types['my_type'] =__( 'My New Coupon Type', 'woocommerce' ); return $discount_types; }
Validate the coupon
add_filter('woocommerce_coupon_is_valid_for_product', 'validate_custom_coupon', 10, 4); function validate_custom_coupon($valid, $product, $coupon, $values){ if ( ! $coupon->is_type( array( 'my_type' ) ) ) { return $valid; } $product_cats = wp_get_post_terms( $product->id, 'product_cat', array( "fields" => "ids" ) ); // SPECIFIC PRODUCTS ARE DISCOUNTED if ( sizeof( $coupon->product_ids ) > 0 ) { if ( in_array( $product->id, $coupon->product_ids ) || ( isset( $product->variation_id ) && in_array( $product->variation_id, $coupon->product_ids ) ) || in_array( $product->get_parent(), $coupon->product_ids ) ) { $valid = true; } } // CATEGORY DISCOUNTS if ( sizeof( $coupon->product_categories ) > 0 ) { if ( sizeof( array_intersect( $product_cats, $coupon->product_categories ) ) > 0 ) { $valid = true; } } // IF ALL ITEMS ARE DISCOUNTED if ( ! sizeof( $coupon->product_ids ) && ! sizeof( $coupon->product_categories ) ) { $valid = true; } // SPECIFIC PRODUCT IDs EXLCUDED FROM DISCOUNT if ( sizeof( $coupon->exclude_product_ids ) > 0 ) { if ( in_array( $product->id, $coupon->exclude_product_ids ) || ( isset( $product->variation_id ) && in_array( $product->variation_id, $coupon->exclude_product_ids ) ) || in_array( $product->get_parent(), $coupon->exclude_product_ids ) ) { $valid = false; } } // SPECIFIC CATEGORIES EXLCUDED FROM THE DISCOUNT if ( sizeof( $coupon->exclude_product_categories ) > 0 ) { if ( sizeof( array_intersect( $product_cats, $coupon->exclude_product_categories ) ) > 0 ) { $valid = false; } } // SALE ITEMS EXCLUDED FROM DISCOUNT if ( $coupon->exclude_sale_items == 'yes' ) { $product_ids_on_sale = wc_get_product_ids_on_sale(); if ( isset( $product->variation_id ) ) { if ( in_array( $product->variation_id, $product_ids_on_sale, true ) ) { $valid = false; } } elseif ( in_array( $product->id, $product_ids_on_sale, true ) ) { $valid = false; } } return $valid; }
Calculate & Apply Discount
add_filter('woocommerce_coupon_get_discount_amount', 'wc_cpn_disc', 10, 5); function wc_cpn_disc($discount, $discounting_amount, $cart_item, $single, $coupon) { // IF TYPE MATCHES PERFORM CUSTOM CALCULATION if ($coupon->type == 'my_type') $discount = $cart_item['quantity'] * 2000; return $discount; }
Sources: