I would like to create a Woocommerce product with an additional text input field which checks if the value entered is unique to that field otherwise outputs a message.
In other words if I enter "dave" and "dave" has been submitted by a different user then I cant proceed with the purchase.
Any help would be much appreciated,
I dont know where to start on this one.
This can be done in a very simple way with 3 small hooked functions:
- The 1st one, add the custom input text field before add to cart button in single product pages
- The 2nd one make the validation, checking that is a unique value
- The 3rd one save the value as product meta data in the array of existing values after validation
The submitted value will be verified for the current product...
The code:
// The product custom field before add-to-cart button - Frontend
add_action( 'woocommerce_before_add_to_cart_button', 'action_before_add_to_cart_button' );
function action_before_add_to_cart_button() {
global $product;
echo '<div>';
woocommerce_form_field( 'custom_unique', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('The label name'),
'placeholder' =>__('Please enter …'),
'required' => true,
), '' );
// For test: displaying existing submitted values (commented - inactive)
// print_r( get_post_meta( $product->get_id(), '_custom_unique_values', true ) );
echo '</div><br>';
}
// Field validation (Checking)
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 20, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity ) {
// Get the custom field values to check
$custom_unic_values = (array) get_post_meta( $product_id, '_custom_unique_values', true );
// Check that the value is unique
if( in_array( $_POST['custom_unique'], $custom_unic_values ) ){
$passed = false ; // Set as false when the value exist
// Displaying a custom message
$message = sprintf( __( 'The value "%s" already exist, try something else…', 'woocommerce' ), sanitize_text_field( $_POST['custom_unique'] ) );
wc_add_notice( $message, 'error' );
}
return $passed;
}
// Save the new unique value in the array of values (as product meta data)
add_action( 'woocommerce_add_to_cart', 'action_add_to_cart', 20, 6 );
function action_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
if( isset($_POST['custom_unique']) ){
// Get the array of existing values
$custom_unic_values = (array) get_post_meta( $product_id, '_custom_unique_values', true );
// append the new value to the array of values
$custom_unic_values[] = sanitize_text_field( $_POST['custom_unique'] );
// Save the appended array
update_post_meta( $product_id, '_custom_unique_values', $custom_unic_values );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.