Woocommerce Get Related Products by Same Sub Category with no Repeate Same Product code example
Example: Woocommerce Get Related Products by Same Sub Category with no Repeate Same Product
add_filter('woocommerce_related_products', 'add_related_products');
function add_related_products($related_product_ids)
{
global $post;
$terms = get_the_terms($post->ID, 'product_cat');
if (count($terms) === 1) {
return $args;
}
$cats = array();
foreach ($terms as $k => $term) {
if ($term->parent === 0) {
unset($terms[$k]);
} else {
$cats[] = $term->term_id;
}
}
$post_ids = get_posts(array(
'post_type' => 'product',
'numberposts' => -1,
'exclude' => $post->ID,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $cats,
),
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $post->ID,
'operator' => 'NOT IN',
),
),
'fields' => 'ids',
));
return $post_ids;
}