This PHP code creates a custom loop for related products in the same category as the current product being viewed on the single product page in WooCommerce. If there are less than 4 products in the same category, products in the same related tag are shown.
How The Code Works
1. Initialization of Variables :
– The function starts by initializing the
$exclude array to exclude the current product ID from the query results.
– Two arrays,
$cat_ids, are initialized to store the term IDs of product tags and categories, respectively.
2. Retrieving Tags and Categories :
– The code retrieves the product tags and categories using
– It loops through the tags and categories, adding their term IDs to the respective arrays.
3. Determining the Taxonomy :
– The code then checks the count of categories
$cat_ids and tags (
– If there are more than 3 products in the same category, it sets the
$taxonomy variable to ‘product_cat’ and uses the category IDs for the query.
– If there are more than 3 products using the same tag but not enough products in the same category, it sets the
$taxonomy variable to ‘product_tag’ and uses the tag IDs for the query.
4. Fallback for Insufficient Categories or Tags :
– If neither condition is met (i.e., there are not enough products in the same category or tag), the code attempts to use the first category (if available) or the first tag.
– If no categories or tags are found, it echoes a message indicating that no relevant categories or tags were found.
5. WC_Product_Query :
– The code then creates a
WC_Product_Query instance to query for related products.
– It specifies parameters such as the number of products to retrieve
order, stock status
stock_status, and the exclusion of the current product
– The tax query is set to filter products based on the determined taxonomy and associated terms.
This logic is designed to dynamically select whether to query related products by category or tag based on the counts of associated terms, with a fallback mechanism if there are insufficient categories or tags.
There’s only 1 step :
Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.