Replies: 1
Hi everyone,
I have an e-commerce website running on WooCommerce, and I’ve set up related products to display on each product page. Each of my products belongs to two categories: a main category and a subcategory, and each product has at least one tag.
Currently, the related products are being displayed based on the product’s category, which is the default behavior. I have also configured it to show 12 related products, but here’s what I want to achieve:
- Priority to Tags: First, I want related products to be shown based on the product’s tag. If there are fewer than 12 products that match the tag, I want the remaining spots to be filled with products from the category.
- Category Only: If the product has no tags, then the related products should only be selected based on the category.
I have added the following custom code to my functions.php to achieve this, but it’s not working as expected:
function custom_related_products_args( $args ) {
global $product;
// Get the current product’s ID
$product_id = $product->get_id();
// Get the current product’s tags
$tags = wp_get_post_terms( $product_id, ‘product_tag’, array( ‘fields’ => ‘ids’ ) );
// If the product has tags, filter related products by tags first
if ( ! empty( $tags ) ) {
$args[‘tax_query’] = array(
array(
‘taxonomy’ => ‘product_tag’,
‘field’ => ‘term_id’,
‘terms’ => $tags,
),
);
}
return $args;
}
add_filter( ‘woocommerce_related_products_args’, ‘custom_related_products_args’ );
Can anyone help me adjust this code to achieve the functionality I want? Any advice or suggestions would be appreciated!