Related Products, which are shown on the single product template, are pulled from your store which share the same tags or categories as the currently viewed product.
For example, if you are looking at a pair of socks which are part of the clothing category, you will see under the Related Products heading products which also belong to this clothing category.
By default, Related Products are sorted randomly (as are manually defined Cross-Sells and Upsells).
Related Products, despite not being a manually defined cross-sell or upsell, act as an additional purchase, potentially increasing your Average Order Value (AOV).
So it makes sense only in-stock related products are shown and out-of-stock related products are hidden.
This code snippet targets only the single product page. It hides all out-of-stock related products and will only show in-stock related products.
Because the code snippet only targets the single product template, out-of-stock products will still be shown elsewhere they are generated like the shop and category pages.
To target other locations, you’ll need to change line 8 in the code.
/**
* Snippet Name: WooCommerce Show Only In Stock Related Products
* Snippet Author: ecommercehints.com
*/
add_action( 'pre_get_posts', 'ecommercehints_in_stock_related_products_only' );
function ecommercehints_in_stock_related_products_only( $query ){
if( is_product() && $query->is_main_query() ) { // Only on the product page where Related Products are shown
$query->set( 'meta_key', '_stock_status' );
$query->set( 'meta_value', 'instock' );
}
}