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

/**
 * @snippet       Get Related Products by Same Sub Category with no Repeate Same Product @ WooCommerce Single
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter('woocommerce_related_products', 'add_related_products');
function add_related_products($related_product_ids)
{
    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.
    'exclude' => $post->ID,
    '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
    ));

    return $post_ids;
}

Tags:

Php Example