skip to Main Content

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


  1. 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:

    <input name="_custom_option" type="text" class="form-control" id="_custom_option" required>
    

    Here is my working example with your code:
    https://jsfiddle.net/SergeyKozlov/ebn40tqx/

    image do here

    Login or Signup to reply.
  2. As your code you can use

    <label>Enter ID: <input name="_custom_option" value="" required></label>
    

    or

    <label>Enter ID: <input name="_custom_option" value="" required="required"></label>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search