How can I make the required field value (required) on the woocommerce product page when adding a product

I added a custom text box field on the add product page in woocommerce. Now I want to make it mandatory. I tried this by passing the argument "required" => true. But that does not work. 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 this does not make the text field mandatory. Please can someone tell me how can I do this?

+4
source share
2 answers

For the requiredHTML5 attribute and other custom attributes, the woocommerce_wp_text_input()function has custom_attributes.

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' )
  )
);
+5

.

// 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 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;

    }

Woocommerce. .

0

Source: https://habr.com/ru/post/1541710/


All Articles