I have added a simple input field just below the short description on a product page. But can’t seem to figure out how to make it a required field, so that you can’t add the product to cart unless this field is filled out. Adding required to the input field isn’t enough.
<label>Enter ID: <input name="_custom_option" value="" required></label>
using this code to create the field
function mic_custom_option() {
global $product;
$id = $product->get_id();
if ($id==14352){
$value = isset( $_POST['_custom_option'] ) ? sanitize_text_field( $_POST['_custom_option'] ) : '';
printf( '<p><label>%s<input name="_custom_option" value="" class="form-control" id="_custom_option" required" /></label></p>', __( 'Enter ID: ', 'www-plugin-textdomain' ), esc_attr( $value ) );
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'mic_custom_option', 9 );
2
Answers
Firstly, your HTML markup is broken.
You can use templates from here:
https://getbootstrap.com/docs/5.3/forms/overview/
Secondly, you must replace the required="" with a required:
Here is my working example with your code:
https://jsfiddle.net/SergeyKozlov/ebn40tqx/
As your code you can use
or