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?!
They wouldn’t.
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_posts
query and add our new functionexclude_oos_related_products
- Inside of that function, we get a list of all out of stock product IDs and set this to be in a variable called
$exclude_ids
- 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
- Done!
Any troubles, leave a comment below.
Works a lot (in 2022). Thank you for share!
Not working in 2023 🙁
Still showing related products with out of stock
Nice, did you know why “woocommerce_output_related_products_args” does not work ?
Thought I finally found it, but not working in 2023/24 woocommerce