This code creates 3 loops for related products and shows them before and after all single products which are out of stock.
Loop 1 displays before the single product and shows products by related category if 5 or more products are in the same category as the current product otherwise it shows a loop of products by related brand.
Loop 2 displays after the single product and shows products by related tag if 5 or more products are assigned the same tag as the current product otherwise it shows a loop of products by related category.
Loop 3 is positioned after Loop 2 and shows products by related category if 5 or more in the same category as the current product otherwise it shows a loop of products by related brand.
All loops display unique products regardless of which taxonomy they are assigned to meaning no duplicate products are displayed on any single product page.
Installation
There’s only 1 step.
Add the code to the end of your child themes functions file or custom functionality plugin and remember to clear caching.
Note : The file includes code to add a custom taxonomy named brand. If you already have code which creates brands, only copy the code starting from line 45.