Completely Disable/Hide Variations with no Price

I recently found myself needing to disable variations that were free, i.e. their price was 0. The reason for this was that the site was viewable in 3 different currencies – USD, GBP, and EUR. If the price was 0 for any variation, then that product was not available in that country. As such, I needed to hide it, for a number of reasons:

  • To change the “From” price from $0, to the next lowest price.
  • To prevent users from selecting an unavailable selection.
  • To remove English based dimensions, like “Size” in millimetres instead of inches.

Fortunately, I was able to do this quite easily with some filter hooks.

The Full Code

The easiest way to explain is to jump right in!

The Filters

We’re adding 5 filters here. It’s not actually as complicated as it looks. Let me explain.

Every variation has an is_visible parameter. If this is true, the variation is classed as visible. If it’s false, the opposite is true. Here we’re checking whether the price is empty, and if it is, we’re saying this particular variation is not visible. Otherwise, we return whatever it would have returned anyway, true or false. Empty in this scenario will be true for zero value, empty strings, etc.

That’s step 1. Step 2 is for us to enable hiding of invisible variations:

WordPress has a built in function named __return_true, which, as you can image, returns true. There’s also __return_false. It just saves us writing our own function to simply return a true value.

So this filter simple says “Yes, I want you to hide variations that are not visible”.

The 3rd step is to modify the min price for each variation.

These filters are almost doing the same thing. They are modifying the price that is returns for the final price, sale price, and regular price, respectively. Each filter calls it’s own function, but they all do this ultimately:

We’re checking if the price is fetching the min value. If it is, we run it through our new function:

This gets all the prices for the product, then runs through our iconic_is_not_empty function to remove any empty values, then gets the current or lowest price from that array and returns it. This basically strips out 0 prices and returns the next lowest one.

Conclusion

That’s it! Add the full code to your theme’s functions.php file and it should work instantly. It could also be tweaked to work slightly differently, based on your requirements, but it’s a good place to get started.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of