Looking at a WooCommerce client recently who has opted to display (albeit not prominently) out of stock products in their store, sometimes we were seeing those OOS (out of stock) products showing up in Related Products.
Since there were 4 slots available, this would sometimes create an undesirable buying experience: why would anyone want to see 3 or 4 out of stock products as “alternative” options?!
There’s several snippets and support topics online about how to exclude out of stock products from Related Products in WooCommerce.
Most of those are out of date now, don’t work, or go about things in not quite the correct manner.
The easiest and most reliable method for 2021 (latest versions of WordPress and WooCommerce) is contained within the following Gist:
This code should go into the functions.php file of your active child theme, or better, a snippets plugin or even better a custom plugin setup to hold such code (so you can turn it off if it’s not working). Never update a parent theme or plugin directly.
You can see what it does:
- Initially, filter the
woocommerce_related_postsquery and add our new function
- Inside of that function, we get a list of all out of stock product IDs and set this to be in a variable called
- Return the difference between the related posts without those exclude IDs to override the original set of related products – minus those excluded (out of stock) IDs
Any troubles, leave a comment below.