Home > database >  Exclude categories from product_categories shortcode using slug
Exclude categories from product_categories shortcode using slug

Time:10-27

<div class="categories">[product_categories limit="10" columns="5" orderby="menu_order"]</div>

Is it possible to hook into product categories shortcode and filter out specific categories from returning (by slug), like you can with products using woocommerce_shortcode_products_query hook.

add_filter( 'woocommerce_shortcode_products_query', 'xaa_remove_category', 50, 3);
function xaa_remove_category( $query_args, $atts, $loop_name ){
    if( is_front_page() ){
        
        $query_args['tax_query'] = array(array( 
        'taxonomy' => 'product_cat', 
        'field' => 'slug', 
        'terms' => ['custom-category-slug'],
        'operator' => 'NOT IN'
        ));
        
    }
    return $query_args;
}

Like this but for product categories

CodePudding user response:

You can woocommerce_product_categories filter hook. try the below code.

add_filter( 'woocommerce_product_categories', 'exclude_product_category', 10, 1 );
function exclude_product_category( $product_categories ){

    $exclude_category = 'test-2'; // your category slug

    foreach ( $product_categories as $key => $product_cat ) {
        if( $product_cat->slug == $exclude_category ){
            unset( $product_categories[$key] );
        }
    }
    
    return $product_categories;

}

CodePudding user response:

Show all categories

[product_categories]

Show all categories but expect ID = 8

  • All category ids: 8, 15, 34, 20, 18, 37, 10
  • See, this last version is missing the "8"!

[product_categories ids="15, 34, 20, 18, 37, 10"]

  • Related