Remove Out of Stock products from WooCommerce Related Products

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:

  1. Initially, filter the woocommerce_related_posts query and add our new function exclude_oos_related_products
  2. 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
  3. 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
  4. Done!

Any troubles, leave a comment below.

Leave a comment