gpt4 book ai didi

php - 通过允许的用户 ID 对 WooCommerce 优惠券添加限制

转载 作者:行者123 更新时间:2023-12-02 02:53:28 25 4
gpt4 key购买 nike

假设我正在使用此代码创建优惠券:

$coupon_code = 'CODEOFF';
$amount = '10';
$discount_type = 'percent';

$coupon = array(
'post_title' => $coupon_code,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', $some_id );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', $some_date );

现在我想将此代码限制为仅供一个用户使用。

可以选择使用 update_post_meta( $new_coupon_id, 'customer_email', '' );,但我的用户没有电子邮件。

如何将此优惠券限制为使用该用户 ID 的用户?

最佳答案

要保持动态,您可以使用以下代码向使用限制选项卡添加一个新字段:

// Add new field - usage restriction tab
function action_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
woocommerce_wp_text_input( array(
'id' => 'customer_user_id',
'label' => __( 'User ID restrictions', 'woocommerce' ),
'placeholder' => __( 'No restrictions', 'woocommerce' ),
'description' => __( 'List of allowed user IDs. Separate user IDs with commas.', 'woocommerce' ),
'desc_tip' => true,
'type' => 'text',
));
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'action_woocommerce_coupon_options_usage_restriction', 10, 2 );

// Save
function action_woocommerce_coupon_options_save( $post_id, $coupon ) {
// Isset
if ( isset ( $_POST['customer_user_id'] ) ) {
$coupon->update_meta_data( 'customer_user_id', sanitize_text_field( $_POST['customer_user_id'] ) );
$coupon->save();
}
}
add_action( 'woocommerce_coupon_options_save', 'action_woocommerce_coupon_options_save', 10, 2 );

您可以在其中输入用户 ID,以逗号分隔。 (见附图)

enter image description here


连同优惠券验证代码:

// Valid
function filter_woocommerce_coupon_is_valid( $valid, $coupon, $discount ) {
// Get meta
$customer_user_id = $coupon->get_meta( 'customer_user_id' );

// NOT empty
if ( ! empty( $customer_user_id ) ) {
// Convert string to array
$customer_user_id = explode( ', ', $customer_user_id );

// Get current user id
$user_id = get_current_user_id();

if ( ! in_array( $user_id, $customer_user_id ) ) {
$valid = false;

if ( ! $valid ) {
throw new Exception( __( 'My error message', 'woocommerce' ), 109 );
}
}
}

return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );

关于php - 通过允许的用户 ID 对 WooCommerce 优惠券添加限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com