**UPDATE 2021**
You can use the following:
```
add_filter( 'woocommerce_product_related_posts_query', 'alter_product_related_posts_query', 10, 3 );
function alter_product_related_posts_query( $query, $product_id, $args ){
global $wpdb;
$query['join'] .= " INNER JOIN {$wpdb->postmeta} as pm ON p.ID = pm.post_id ";
$query['where'] .= " AND pm.meta_key = '_stock_status' AND meta_value = 'instock' ";
return $query;
}
```
Code goes in functions.php file of your active child theme (or active theme).
>Now **we need to remove "related products" cached data** deleting the related transients to flush this cache *(thanks to [@Cody Rees][1])*.
**There is 2 ways to do it:**
1). The **easiest** way:
Go to admin Woocommerce > Status > Tools > WooCommerce transients and press on "Clear transcients".
2). The other way targeting specific related transients to be deleted:
Add the following code and save:
```
add_action('init', 'delete_related_products_cached_data');
function delete_related_products_cached_data() {
global $wpdb;
$wpdb->query("DELETE FROM {$wpdb->prefix}options WHERE `option_name` LIKE '_transient_wc_related_%'");
}
```
Code goes in functions.php file of your active child theme (or active theme).
**Run it only once** by browsing any page of your web site and remove it.
[1]:
[To see links please register here]