Idromet Sider
Idromet Sider

Reputation: 21

Hide subcategories products in the macro-category in Woocommerce

I would like to show products and subcategories of a macro-category but I DON'T want to show the products of the subcategories.

Here's an example of my problem: http://www.idromet.it/jml/wp/categoria-prodotto/prodotti/tubi-raccordi-acciaio-al-carbonio/

"Raccordi in ghisa zincati" is showed 2 times because the first is the category (and its right), the second one is the product of that sub-category (and I don't want to show it in here).

Upvotes: 2

Views: 4789

Answers (2)

XanderMan
XanderMan

Reputation: 143

This code shows products from the current category only. Hiding parent and child categories. Code can be triggered with shortcode [cwpai_current_category_products]

    function cwpai_show_products_from_current_category() {
        if (!is_product_category()) return;

$current_term = get_queried_object();
$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => $current_term->term_id,
            'include_children' => false
        )
    )
);
$products = new WP_Query($args);

if ($products->have_posts()) {
    echo '<ul class="products">';
    while ($products->have_posts()) : $products->the_post();
        wc_get_template_part('content', 'product');
    endwhile;
    echo '</ul>';
}

wp_reset_postdata(); }

add_shortcode('cwpai_current_category_products', 
'cwpai_show_products_from_current_category');

   function cwpai_hide_subcategory_icons() {
    if (is_product_category()) {
        add_filter('subcategory_archive_thumbnail', '__return_false');
    }
}

add_action('woocommerce_before_main_content', 'cwpai_hide_subcategory_icons');

Upvotes: 0

Giuseppe Riboni
Giuseppe Riboni

Reputation: 81

The code below should be pasted in the functions.php file located in your child theme folder.

function exclude_product_cat_children($wp_query) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
    $wp_query->set('tax_query', array( 
                                    array (
                                        'taxonomy' => 'product_cat',
                                        'field' => 'slug',
                                        'terms' => $wp_query->query_vars['product_cat'],
                                        'include_children' => false
                                    ) 
                                 )
    );
  }
}  
add_filter('pre_get_posts', 'exclude_product_cat_children'); 

Upvotes: 8

Related Questions