编程语言
首页 > 编程语言> > php-WooCommerce:检查优惠券是否有效

php-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';
}

该代码已经过测试并且功能齐全.

参考

> WC_API_Coupons::get_coupon( $id, $fields )

标签:coupon,woocommerce,hook-woocommerce,wordpress,php
来源: https://codeday.me/bug/20191026/1938135.html