Skip to content

Instantly share code, notes, and snippets.

@ARCHTKT
Last active July 3, 2021 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ARCHTKT/3f997b6ce728cf5a1e19d884782e629a to your computer and use it in GitHub Desktop.
Save ARCHTKT/3f997b6ce728cf5a1e19d884782e629a to your computer and use it in GitHub Desktop.
WooCommerce coupon usage restriction by allowed user roles
<?php /* No copiar esta linea */
// Add new field - Coupon usage restriction tab
function archtkt_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
woocommerce_wp_text_input( array(
'id' => 'customer_user_role',
'label' => __( 'User role restrictions', 'woocommerce' ),
'placeholder' => __( 'No restrictions', 'woocommerce' ),
'description' => __( 'List of allowed user roles. Separate user roles with commas.', 'woocommerce' ),
'desc_tip' => true,
'type' => 'text',
));
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'archtkt_woocommerce_coupon_options_usage_restriction', 10, 2 );
// Save role as coupon usage restriction
function archtkt_woocommerce_coupon_options_save( $post_id, $coupon ) {
update_post_meta( $post_id, 'customer_user_role', $_POST['customer_user_role'] );
}
add_action( 'woocommerce_coupon_options_save', 'archtkt_woocommerce_coupon_options_save', 10, 2 );
// Validate user role at coupon usage
function archtkt_filter_woocommerce_coupon_is_valid( $is_valid, $coupon, $discount ) {
// Get meta
$customer_user_role = $coupon->get_meta('customer_user_role');
// NOT empty
if( ! empty( $customer_user_role ) ) {
// Convert string to array
$customer_user_role = explode(', ', $customer_user_role);
// Get current user role
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
// Start with not valid coupon
$is_valid = false;
if( ! empty( $roles ) ) {
foreach ($roles as $role) {
// Compare
$compare = in_array( $role, $customer_user_role );
if ( $compare ) {
$is_valid = true;
}
}
}
}
return $is_valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'archtkt_filter_woocommerce_coupon_is_valid', 10, 3 );
@jessicaJ019
Copy link

Thanks for your code. It's great and useful.
If I want to take a noice, this coupon is for only role. how can do it?
$is_valid = false . ' this coupon is for only role.'; < that's ok?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment