WooCommerce:检查优惠券是否有效 [英] WooCommerce: Check if coupon is valid
本文介绍了WooCommerce:检查优惠券是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查优惠券是否仍然有效(尚未达到使用限制),并在这种情况下显示内容.
I am trying to check if a coupon is still valid (hasn't reached its usage limit) and display content under this condition.
之所以这样做,是因为我希望能够向特定的访问者发放优惠券代码,但是显然不想发放已经达到其使用限制的优惠券.
The reason for this is that I want to be able to hand out a coupon code to particular visitors, but obviously don't want to hand out a coupon that has already reached it's usage limit.
我正在尝试使用PHP来实现这一点,并想象代码是这样的:
I am trying to achieve this with PHP and imagine the code to be something like this:
<?php if (coupon('mycouponcode') isvalid) {
echo "Coupon Valid"
} else {
echo "Coupon Usage Limit Reached"
} ?>
这里的任何帮助都会很棒:)
Any help here would be great :)
推荐答案
$code = 'test123';
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);
$coupon_data = array(
'id' => $coupon->id,
'code' => $coupon->code,
'type' => $coupon->type,
'created_at' => $coupon_post->post_date_gmt,
'updated_at' => $coupon_post->post_modified_gmt,
'amount' => wc_format_decimal($coupon->coupon_amount, 2),
'individual_use' => ( 'yes' === $coupon->individual_use ),
'product_ids' => array_map('absint', (array) $coupon->product_ids),
'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
'usage_count' => (int) $coupon->usage_count,
'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', $coupon->expiry_date) : null,
'enable_free_shipping' => $coupon->enable_free_shipping(),
'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
'exclude_sale_items' => $coupon->exclude_sale_items(),
'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
'customer_emails' => $coupon->customer_email,
'description' => $coupon_post->post_excerpt,
);
$usage_left = $coupon_data['usage_limit'] - $coupon_data['usage_count'];
if ($usage_left > 0) {
echo 'Coupon Valid';
}
else {
echo 'Coupon Usage Limit Reached';
}
该代码已经过测试并且功能齐全.
The code is tested and fully functional.
参考
这篇关于WooCommerce:检查优惠券是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文