I was browsing the Advanced WooCommerce group on Facebook and saw a post that was over 24 hours old and had no comments. Most posts get at least a few replies and many of them are within a few hours of the question being posted.
The post asked if anyone knew how to make the product weight a required field when editing a product.
I did a few experiments to see if any field was required when editing a product – if so I would copy their configuration. Surprisingly no field was required, not even a price, description, short description or even a title!! (A title is needed otherwise you get a 404 error when you try to view the new product, but there is no error or warning message in the Edit Product page!)
A few Google searches showed me the
required="required" html input element attribute. I used Chrome Developer Tools to add this to the weight field. When I tried to save the product with no weight value specified it displayed a message: Please fill out this field. This message is from the browser as it is the browser that is enforcing the requirement for the field to have a value. This is a great start so I went looking to see if I could use add_filter() to add this to the input element.
No apply_filters() option
I found the weight field created by a call to woocommerce_wp_text_input() in includes/admin/wc-meta-box-functions.php. There are no apply_filters calls in that file so I would not be able to modify the element there.
I found the definition of woocommerce_wp_text_input() in includes/admin/meta-boxes/views/html-product-data-shipping.php. Unfortunately there are no apply_filters() calls there either.
Half the job done
The code did its job – the input element now had a
required attribute (not
required="required" but it still worked). The product would not be created or updated if the weight field did not have a value. Unfortunately there was no error message – the browser message only appeared if the field was visible i.e. if the Shipping tab was visible.
The second half of the job was to display an error message and set focus to the weight field. The new code checked the weight field’s value and if empty or 0, it ‘clicked’ the Shipping tab and set focus to the weight field.
Your Mission, Should You Choose To Accept It…
This code could be expanded to make any field required – maybe an array of field names (and the ID of the tab there are in – to set focus if required) that would have the
required attribute added and then each one checked. Obviously if multiple fields fail the test you cannot set focus to each of them. An explanatory message box (maybe a nice one via jQuery UI if it is loaded) would suffice. The main code could be moved to its own JS file and the dynamic data loaded with wp_localize_script(). That’s a job for the reader 🙂