Home » WooCommerce: Exclude Category from [products] Shortcode

WooCommerce: Exclude Category from [products] Shortcode

by Tutor Aspire

The WooCommerce “products” shortcode displays all products in your shop. There is even an attribute called “category” where you can specify comma-separated list of category slugs in order to further filter the output.

What you can’t do is define a list of unwanted categories (think of “uncategorized” for example) i.e. a list of categories you want to exclude from the products shortcode output.

So, here’s the fix, enjoy!

WooCommerce: exclude category from shortcodes
WooCommerce: exclude category from shortcodes

PHP Snippet: Exclude Category from “products” Shortcode

Let’s say we want to remove the category “black” (see above example) from the “products” shortcode. The snippet to place in your functions.php is very simple:

/**
 * @snippet       Exclude Category from products Shortcode
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 6
 * @donate $9     https://www.tutoraspire.com
 */

add_filter( 'woocommerce_shortcode_products_query', 'tutoraspire_exclude_cat_shortcodes' );
 
function tutoraspire_exclude_cat_shortcodes( $query_args ){ 
$query_args['tax_query'][] = array( array( 
'taxonomy' => 'product_cat', 
'field' => 'slug', 
'terms' => array( 'black' ), // Don't display products from this category
'operator' => 'NOT IN'
)); 
return $query_args;
}

You may also like