19/07/2021
Woocommerce小贴士:
如果你是经常有使用COUPON功能的,你也许会有一个烦恼就是,不知如何设定只是指定的用户身份比如AGENT, 还是VIP才可以使用。一般要设定如此,都是需要付费,今天我教大家如何免费做些客制,就可以达成你要的需求。
以下的例子会教您如何增加一个新的用户身份,以让您可以在COUPON SETTING里面设定所可以享有的优惠。
谨记以下的程序码需要添加在子主题里面的function.php或是code snippet里面。
// Step 1: Add New Field - User Role Restrictions (Set which user role is allowed to use coupon)
function action_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
woocommerce_wp_text_input( array(
'id' => 'allowed_user_role',
'label' => __( 'Allowed User Roles', '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', 'action_woocommerce_coupon_options_usage_restriction', 10, 2 );
// Step 2: Update new setting into coupon option
function action_woocommerce_coupon_options_save( $post_id, $coupon ) {
update_post_meta( $post_id, 'allowed_user_role', $_POST['allowed_user_role'] );
}
add_action( 'woocommerce_coupon_options_save', 'action_woocommerce_coupon_options_save', 10, 2 );
// Step 3: Check for validity of the coupon by user role
function filter_woocommerce_coupon_is_valid( $is_valid, $coupon, $discount ) {
// Get meta
$customer_user_role = $coupon->get_meta('allowed_user_role');
// If User Role is 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;
// If matched, compare will be empty
$compare = array_diff( $roles, $customer_user_role );
// If NOT empty
if ( ! empty ( $compare ) ) {
$is_valid = false;
}
}
return $is_valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );
** 若你已经增加好了,刷新后台,你将会发现COUPON SETTING里面会增添多一个设定,那就是ALLOWED USER ROLES,你可以设定多个身份进去比如customer,subscriber等等,切记输入的时候不能使用大写capital letter。