woocomerce product page input validation
// 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 );
}
}