Menu Close

WooCommerce: Exclude Category from ‘products’ Shortcode

default

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 CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'woocommerce_shortcode_products_query', 'bbloomer_exclude_cat_shortcodes' );
 
function bbloomer_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;
}
View Source
Posted in WooCommerce Tips