Enhance last year's code to make multiple WooCommerce product fields required.
Early last year I wrote code to make the weight field required when editing a product in WooCommerce. During the summer John asked about making product dimensions required (length, width and height). They modified my code but it wasn’t working.
I fired up my local XAMPP environment and downloaded the original code. Instead of duplicating the ‘script’ blocks I made the necessary changes inside the ‘click’ handler.
Make an array
I felt that the code was a bit long as the value checking code was repeated for each field. I decided to put the field info into an array and loop through that. The array elements looked like:
[ 'Weight', '#_weight', 'Shipping', '.shipping_tab > a' ],
Each element of the array has the nice name (‘Weight‘), the field ID (‘#_weight‘), the nice name of the tab with the field (‘Shipping‘) and then the selector to open the tab (‘.shipping_tab > a‘).
The loop reduced the size of the code significantly and it is much easier to maintain. It can replace the code from last year.