Last active
July 3, 2021 07:26
-
-
Save ARCHTKT/3f997b6ce728cf5a1e19d884782e629a to your computer and use it in GitHub Desktop.
WooCommerce coupon usage restriction by allowed user roles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?