问题描述
我在 woocommerce 客户仪表板上创建了“文本字段”,该字段用于兑换优惠券。假设我在要使用的 woocommerce 优惠券上设置了优惠券代码“BIRTHDAY29”。
用户在我的“文本字段”上输入“BIRTHDAY29”,然后点击按钮“REDEEM”,这样交易就会以编程方式应用到他们的交易历史中。
我如何知道该用户使用了“BIRTHDAY29”优惠券多少次?我想检查该用户是否曾经使用过“BIRTHDAY29”,然后我想做“某事..”如果该用户曾经使用过 BIRTHDAY29。
希望你们明白我的意思,谢谢!!
解决方法
给你:
function coupon_usage_for_customer( $coupon_code,$user_id = NULL,$email = NULL )
{
$usage = 0;
// There must either be a user ID or email address
if( empty( $user_id ) && empty( $email ) )
return FALSE;
$params = [
'limit' => -1,'type' => 'shop_order'
];
if( ! empty( $user_id ) ){
$params['customer_id'] = $user_id;
}
else if( ! empty( $email ) ){
$params['billing_email'] = $email;
}
// Get orders of customer
$orders = wc_get_orders( $params );
// Check if coupon used
foreach( $orders as $order )
{
$coupons_used = $order->get_coupon_codes();
if(
is_array( $coupons_used ) &&
in_array( $coupon_code,$coupons_used )
){
$usage++;
}
}
return $usage;
}
add_action('woocommerce_after_register_post_type',function(){
$user_id = 12345;
$email = 'oneguy@example.com';
$birthday29usage = coupon_usage_for_customer( 'BIRTHDAY29',$user_id,$email );
if( ! $birthday29usage )
echo 'The user has not birthday 29ed...';
});