This is a quick little ‘how to’ that came up in a recent client WooCommerce request. The client wanted to add the text ‘sold out’ to the variable product configuration dropdowns on the product page to make it more clear to customers when a variation was out of stock:
woocommerce/assets/js/add-to-cart-variation.js in an anonymous function callback which is invoked every time the page loads, or the variable product is configured by the user, and ensures that the correct product options are displayed, and enabled or disabled. Luckily for us this function fires a custom DOM event named ‘woocommerce_update_variation_values’, allowing us to listen to changes and manipulate the dropdowns to add our custom text.
This binds to the ‘woocommerce_update_variation_values’ event, and loops through the variation options, checking for disabled options and adding in the ‘sold out’ text if needed, and removing the ‘sold out’ text from the active options if needed. Of course this solution would fail if your product option name ended with the string ” – sold out”, but that would just be silly.
Add this to your own Custom Plugin, or into your theme functions file. Note: in order for the procedure described within this article to work, you must go to WooCommerce > Settings > Inventory, and ensure that “Hide out of stock items from the catalog” is checked. Without that option enabled the results will be less than impressive. Also, any products that you want to enable this on must be configured to not allow backorders: edit the product and go to Product Data > Inventory and set Allow Backorders? to “Do not allow”. If you use this basic recipe to customize the variable product dropdowns in some other new or creative way, let us know in the comments section below!