I’m creating a custom coupon applying functionality to the order pay page, in WordPress & WooCommerce. So people can apply coupons directly to the order and proceed to payment.
This is the code that handles the coupon application to the order. This works fine with normal coupons from WooCommerce. However, when using Gift Cards from WooCommerce Smart Coupons, it does not work. It applies the coupon, but the value of that coupon applied to the order is always equal to 0 for some reason.
$coupon_code = sanitize_text_field($_POST['coupon_code']);
$coupon = new WC_Coupon($coupon_code);
if (!$coupon->get_id()) {
wp_send_json_error('Invalid coupon.');
}
$order->apply_coupon($coupon);
$order->calculate_totals();
$order->save();
Here is the part of the code relevant to the question.
What should I do to handle the cases where someone enters a gift card from Smart Coupons?
I have tried searching the documentation about WC Smart Coupons but there was nothing about instantiating WC Smart Coupon / Gift Card classes through code. Which left me wondering about the possibility of implementing this through code.
I have tried applying the code directly in the backend, in the WooCommerce dashboard, and it actually applies the gift card with the right amount to the order. (I thought there might have been a compatibility issue between the gift card and the order itself)
Alex George is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.