Home / eCommerce / Restrict Coupons by Shipping Methods
Duplicate Snippet

Embed Snippet on Your Site

Restrict Coupons by Shipping Methods

To find your exact shipping method IDs, you can use either of these quick methods:

1. The URL Method: Go to WooCommerce → Settings → Shipping, click into each shipping zone, and hover over the shipping method link. The instance ID will be visible in your browser's URL preview at the bottom (e.g., instance_id=1 translates to flat_rate:1).

2. The Debug Method: Alternatively, you can temporarily add var_dump( WC()->session->get('chosen_shipping_methods') ); to your template files on a staging environment to see exactly which active IDs are currently in use during checkout.

Code Preview
php
<?php
add_filter( 'woocommerce_coupon_is_valid', function( $valid, $coupon, $discount ) {
      // List the coupon codes to restrict (lowercase)
      $restricted_coupons = [ 'your-coupon-code' ];
      if ( ! in_array( strtolower( $coupon->get_code() ), $restricted_coupons, true ) ) {
          return $valid;
      }
      // Allowed shipping method IDs — find these in WooCommerce > Settings > Shipping
      // Format is usually 'method_id:instance_id', e.g. 'flat_rate:1', 'free_shipping:3', 'local_pickup:2'
      $allowed_methods = [ 'flat_rate:1', 'free_shipping:10'  ];
      $chosen = WC()->session ? WC()->session->get( 'chosen_shipping_methods', [] ) : [];
      foreach ( $chosen as $method ) {
          if ( in_array( $method, $allowed_methods, true ) ) {
              return $valid;
          }
      }
      return false;
  }, 10, 3 );

Comments

Add a Comment