WooCommerce:检查优惠券是否有效
我试图检查优惠券是否仍然有效(尚未达到其使用限制)并在此条件下显示内容。WooCommerce:检查优惠券是否有效
原因是我希望能够向特定访客发放优惠券代码,但显然不想分发已经达到其使用限制的优惠券。
我想用PHP来实现这一点,想象中的代码是这样的:
<?php if (coupon('mycouponcode') isvalid) {
echo "Coupon Valid"
} else {
echo "Coupon Usage Limit Reached"
} ?>
:)
$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';
}
的代码测试完全在这里的任何帮助将是巨大的功能。
参考
这总是返回“优惠券使用限制达到”。我已经用无数优惠券(有效,过期,用完,剩余使用等)替换test123,但没有快乐:( – NuclearApe
@NuclearApe:有任何有效的优惠券打印'$ coupon_data ['usage_limit']','$ coupon_data ['usage_count ']'和'$ coupon_data ['expiry_date']'看看他们回来了什么。 –
只是为了说明:WC_Coupon类('is_valid()'和'is_valid_for_cart()')有两个相关的方法。不幸的是,他们不工作... **有一个** bug **,因为他们**总是返回false **。所以我发布了一个线程在WordPress> Woocommerce支持线程:https://wordpress.org/支持/主题/ wc_coupon-is_valid-method-always-return-false/ – LoicTheAztec
优惠券取决于很多标准,所以您只需要使用限制? –
@RaunakGupta是的,使用限制是我感兴趣的唯一标准:) – NuclearApe