gpt4 book ai didi

php - 如果客户在 WooCommerce 的先前订单中使用过相关优惠券,则限制使用优惠券

转载 作者:行者123 更新时间:2023-12-04 07:32:55 26 4
gpt4 key购买 nike

我正在寻找一种方法来限制优惠券的使用,并在客户之前在 WooCommerce 中使用过之前订单中的相关优惠券时显示错误消息。
通过相关优惠券,我的意思是:在购物车/结帐页面上与当前插入的优惠券一起出现在预定义数组中的优惠券代码。在此基础上进行比较。
我的代码尝试:

add_filter( 'woocommerce_coupon_is_valid', 'specific_coupons_valid', 10,
3 );
function specific_coupons_valid( $is_valid, $coupon, $discount ){
$coupon_codes = array( 'free10', 'free20', 'free30' );

$args = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
);

$coupons = get_posts( $args );

if( in_array( $coupons, $coupon_codes ) ) {
$is_valid = false;
}

return $is_valid;
}
任何帮助表示赞赏

最佳答案

如果客户之前在 WooCommerce 的先前订单中使用过相关优惠券,要限制优惠券的使用,您可以使用:

// Compare & return true OR false
function compare_related_coupon_codes( $current_coupon_code ) {
// Add multiple coupon codes to compare, seperated by a comma
$compare_coupon_codes = array( 'coupon1', 'coupon2', 'coupon3' );

// Default
$valid = true;

// When the current coupon code has to be compared with other coupon codes
if ( in_array( $current_coupon_code, $compare_coupon_codes ) ) {
// Get user ID
$user_id = get_current_user_id();

// Get the WC_Customer instance Object
$customer = New WC_Customer( $user_id );

// Billing email
$email = $customer->get_billing_email();

// Loop through
foreach ( $compare_coupon_codes as $coupon_code ) {
// Get the WC_Coupon instance Object
$coupon_obj = New WC_Coupon( $coupon_code );

// If one of the coupons has already been used by the customer
if ( array_intersect( array( $user_id, $email ), $coupon_obj->get_used_by() ) ) {
$valid = false;
break;
}
}
}

// Return
return $valid;
}

// Valid
function filter_woocommerce_coupon_is_valid( $is_valid, $coupon, $discount ) {
if ( ! is_user_logged_in() ) return $is_valid;

// Get current applied coupon code
$current_coupon_code = strtolower( $coupon->get_code() );

// Call function, true OR false
return compare_related_coupon_codes( $current_coupon_code );
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );

// Error
function filter_woocommerce_coupon_error( $err, $err_code, $coupon ) {
if ( ! is_user_logged_in() ) return $err;

// Get current applied coupon code
$current_coupon_code = strtolower( $coupon->get_code() );

// Validation, call function, true OR false
if ( intval( $err_code ) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED && compare_related_coupon_codes( $current_coupon_code ) == false ) {
$err = __( 'My coupon error', 'woocommerce' );
}

return $err;
}
add_filter( 'woocommerce_coupon_error', 'filter_woocommerce_coupon_error', 10, 3 );

通过在我的答案中添加的评论标签进行解释
相关: Coupon daily time range in WooCommerce

关于php - 如果客户在 WooCommerce 的先前订单中使用过相关优惠券,则限制使用优惠券,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67868421/

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