This code creates a custom product loop for related products. It displays products related to the current product if “out of stock”. If there’s 4 or more related products by tag, the loop displays products by tags. If there’s less than 4, products are displayed by the same category as the current product.
On top of this the code :
- Removes duplicate products and will not include the same product as the current product in the loop.
- Enables you to change the taxonomy so you can display related products by custom taxonomy like brand if less than x number pf products exist in the same category or tag as the current product.
- Enables you to display your products before or after the single product.
Copy & paste the PHP code to the end of your child themes functions file or custom functionality plugin.
- Remember to clear caching & WooCommerce term transients.