Home / eCommerce / Custom Restriction: Category-Specific Subtotal
Duplicate Snippet

Embed Snippet on Your Site

Custom Restriction: Category-Specific Subtotal

Before saving the snippet, please update the three variables at the top of the function to match your store:

1. Change 'your-coupon-code' to the exact name of the coupon you created in Step 1.
2. The $threshold is already set to 5000.00.
3. Change array( 12, 34 ) to the actual comma-separated Category IDs that you want to qualify for this promotion.

Once active, WooCommerce will calculate the cart subtotal purely based on those specific categories. If the total is below $5,000, the coupon will be rejected (or removed if quantities drop).

Code Preview
php
<?php
add_filter( 'woocommerce_coupon_is_valid', 'custom_category_subtotal_coupon_gate', 20, 2 );
  function custom_category_subtotal_coupon_gate( $valid, $coupon ) {
      $target_coupon = 'your-coupon-code'; // lowercase coupon code
      $threshold     = 5000.00;
      $category_ids  = array( 12, 34 ); // replace with actual product category IDs
      if ( strtolower( $coupon->get_code() ) !== $target_coupon ) {
          return $valid;
      }
      if ( ! WC()->cart ) {
          return false;
      }
      $category_subtotal = 0.0;
      foreach ( WC()->cart->get_cart() as $item ) {
          foreach ( $category_ids as $cat_id ) {
              if ( has_term( $cat_id, 'product_cat', $item['product_id'] ) ) {
                  $category_subtotal += wc_get_price_excluding_tax(
                      $item['data'],
                      array( 'qty' => $item['quantity'] )
                  );
                  break;
              }
          }
      }
      if ( $category_subtotal < $threshold ) {
          throw new \Exception(
              sprintf(
                  'You have not met the %s%s minimum spend on qualifying categories.',
                  get_woocommerce_currency_symbol(),
                  number_format( $threshold, 2 )
              )
          );
      }
      return $valid;
  }

Comments

Add a Comment