我正在尝试检查优惠券是否仍然有效(尚未达到使用限制),并在这种情况下显示内容。

原因是我希望能够将优惠券代码分发给特定的访问者,但显然不希望分发已达到其使用限制的优惠券。

我正在尝试使用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 )
  • 关于php - WooCommerce:检查优惠券是否有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39745791/

    10-14 15:26