6

I have added custom text box field in my add product page in woocommerce. Now i want to make it required (compulsory). I tried it by passing argument "required"=>true. but it is not working. Please see below code

woocommerce_wp_text_input(
  array(
    'id' => 'special_price',
    'label' => __( 'Wholesaler Price *', 'woocommerce' ),
    'placeholder' => '',
    'desc_tip' => 'true',
    'required' => 'true',
    'description' => __( 'Enter wholesaler price here.', 'woocommerce' )
  )
);

but it is not making textbox compulsory. Please can anyone tell how can i do this?

Vidhi
  • 2,026
  • 2
  • 20
  • 31

2 Answers2

10

For the required HTML5 attribute and other custom attributes woocommerce_wp_text_input() function has custom_attributes option.

woocommerce_wp_text_input(
  array(
    'id' => 'special_price',
    'label' => __( 'Wholesaler Price *', 'woocommerce' ),
    'placeholder' => '',
    'desc_tip' => 'true',
    'custom_attributes' => array( 'required' => 'required' ),
    'description' => __( 'Enter wholesaler price here.', 'woocommerce' )
  )
);
Danijel
  • 12,408
  • 5
  • 38
  • 54
0

You can modify the following code as per your need.

// Validate when adding to cart
        add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validation_custom', 10, 3 );

/  validation

    function woocommerce_add_to_cart_validation_custom($passed, $product_id, $qty){

        global $woocommerce;

$option = ''; // your custom field's name

   if( isset($_POST[sanitize_title($option)]) && $_POST[sanitize_title($option)] == '' )
        $passed = false;

    if (!$passed)
        $woocommerce->add_error( sprintf( __('"%s" is a required field.', 'woocommerce'), $option) );

        return $passed;

    }

For even more options while adding a product in the cart you may find How to add a custom text box value to cart session array in Woocommerce my this answer helpful.

Community
  • 1
  • 1
maksbd19
  • 3,785
  • 28
  • 37