add_filter('woocommerce_related_products_args', 'filter_woocommerce_related_products_args');

function filter_woocommerce_related_products_args($args)
{
    global $post;

    // get the cats this product is in
    $terms = get_the_terms($post->ID, 'product_cat');

    // if there is only one category jump out.
    if (count($terms) === 1) {
        return $args;
    }

    $cats = array();
    // remove anything that is a parent cat
    foreach ($terms as $k => $term) {
        if ($term->parent === 0) {
            unset($terms[$k]);
        } else {
            // build list of terms we do want (children)
            $cats[] = $term->term_id;
        }
    }

    $post_ids = get_posts(array(
        'post_type' => 'product',
        'numberposts' => -1, // get all posts.
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $cats,
            ),
            // Remove current product
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $post->ID,
                'operator' => 'NOT IN',
            ),
        ),
        'fields' => 'ids', // Only get post IDs
    ));

    // Alter the query
    $args['post__in'] = $post_ids;

    return $args;
}
Geef een reactie 0