I'm building some functionality in WooCommerce that allows users to input an externally generated voucher code when adding a product to the cart. This voucher code is then checked to see if it's been previously used and if not I want to apply a generic coupon code to the order.
I have the validation working using the below code
// Define field label name
function get_field_label_name()
{
return __("Voucher");
}
// Add a custom product note below product meta in single product pages
add_action('woocommerce_before_single_variation', 'my_product_custom_field', 100);
function my_product_custom_field()
{
$voucher_check = get_field('voucher');
$voucher_text = get_field('voucher_text');
if ($voucher_check) {
echo '<div class="vouchers_single">';
echo '<p>' . $voucher_text . '</p>';
woocommerce_form_field('custom_field1', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => get_field_label_name(),
'placeholder' => __("The field placeholder…"),
'required' => true, // Or false
), '');
echo '</div>';
}
}
// Check if the custom field value is unique
add_filter('woocommerce_add_to_cart_validation', 'wc_add_on_feature', 20, 3);
function wc_add_on_feature($passed, $product_id, $quantity)
{
if (isset($_POST['custom_field1']) && !empty($_POST['custom_field1'])) {
global $wpdb;
$label = get_field_label_name();
$value = sanitize_text_field($_POST['custom_field1']);
// Check if value exits already
$result = $wpdb->get_var("
SELECT COUNT(meta_value) FROM {$wpdb->prefix}woocommerce_order_itemmeta
WHERE meta_key LIKE '$label' AND meta_value LIKE '$value'
");
// If it exist we don't allow add to cart
if ($result > 0) {
// Display an error notice
wc_add_notice(sprintf(__('This "%s" input already exist. Please choose another one…'), $value), 'error');
$passed = false;
}
}
return $passed;
}
I also have this code snippet to apply the code
add_action('woocommerce_before_cart_table', 'ts_apply_discount_to_cart');
function ts_apply_discount_to_cart()
{
$order_total = WC()->cart->get_subtotal();
if ($order_total > 250) {
$coupon_code = 'retrofitwest';
if (!WC()->cart->add_discount(sanitize_text_field($coupon_code))) {
wc_print_notices();
}
}
}
But what filter do I need to use to apply the coupon once the custom_field validation is passed?
Any help would be greatly appreciated.