Exclude a product category from Related products in WooCommerce

Refresh

March 2019

Views

17 time

3

I am trying to exclude a product category (id: 78) from the related products section in WooCommerce. I have a custom query already in place which only shows related products from the child category.

This is my code:

<?php global $post, $product;

if (empty($product) || !$product->exists()) {
    return;
}

$subcategories_array = array(0);
$all_categories = wp_get_post_terms($product->id, 'product_cat');
foreach ($all_categories as $category) {
    $children = get_term_children($category->term_id, 'product_cat');
    if (!sizeof($children)) {
    $subcategories_array[] = $category->term_id;
    }
}

if (sizeof($subcategories_array) == 1) {
    return array();
}

$args = array(
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'post_type' => 'product',
    'category__not_in' => array( 78 ),
    'fields' => 'ids',
    'meta_query' => $meta_query,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => $subcategories_array,
        )
    )
);

$wp_query = new WP_Query($args);

if ($wp_query->have_posts()):
    ?>

    <section class="related products">

    <h2><?php esc_html_e('Related products', 'woocommerce'); ?></h2>

    <?php woocommerce_product_loop_start(); ?>

    <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

        <?php
        global $post, $product;

        $post_object = get_post($product->get_id());

        setup_postdata($GLOBALS['post'] = & $post_object);

        wc_get_template_part('content', 'product');
        ?>

    <?php endwhile; ?>

    <?php woocommerce_product_loop_end(); ?>

    </section>

    <?php
endif;

wp_reset_postdata();

However excluding the aforementioned product category doesn't seem to be working as I expected.

Any help is appreciated.

1 answers

0

Woocommerce product categories is a custom taxonomy and can't work as Wordpress categories in a WP_Query using category__not_in … Instead try to combine that in the existing tax_query.

Also on your existing tax_query, for fields argument you need to replace id by term_id (which is enabled by default, so you can remove the line)
see WP_Query Taxonomy Parameters official documentation

Try the following:

$args = array(
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'post_type' => 'product',
    'fields' => 'ids',
    'meta_query' => $meta_query,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'terms'    => $subcategories_array,
        ),
        array(
            'taxonomy' => 'product_cat',
            'terms'    => array( 78 ),
            'operator' => 'NOT IN',
        )
    )
);

It should work.