# Restrict Coupon Codes to Certain Roles

> Makes chosen coupon codes work only for customers with specific roles, such as staff discount codes or trade-only promotions.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, coupons, roles, restrictions
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-coupon-for-roles/

## Code

```php
$wpide_role_coupons = array( // Coupon code => allowed roles.
    'staff20' => array( 'shop_manager', 'administrator', 'editor' ),
    'trade10' => array( 'wholesale_customer' ),
);

add_filter( 'woocommerce_coupon_is_valid', function ( $valid, $coupon ) use ( $wpide_role_coupons ) {
    $code = wc_format_coupon_code( $coupon->get_code() );

    foreach ( $wpide_role_coupons as $restricted => $roles ) {
        if ( wc_format_coupon_code( $restricted ) !== $code ) {
            continue;
        }

        if ( ! is_user_logged_in() || ! array_intersect( $roles, (array) wp_get_current_user()->roles ) ) {
            throw new Exception( esc_html( 'Sorry, this coupon is not available for your account.' ), 100 );
        }
    }

    return $valid;
}, 10, 2 );
```

## Notes

Codes are matched case-insensitively, and guests can never use these coupons.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Restrict Coupon Codes to Certain Roles" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
