A client of mine had to style a WooCommerce product category page but ONLY if it was a subcategory. So I decided to add a “subcategory” class to the HTML body, so that they could target this in their custom CSS.

As usual, the PHP is quite easy: I check if the current page is a product category, then if the category has “parents” and only in this case add a body class. Pretty easy!

WooCommerce: detect if current page is a subcategory

PHP Snippet: Detect if Current Page is a Subcategory – WooCommerce


/**
* @snippet 	Add "Subcategory" Class to HTML Body
* @how-to 	Get CustomizeWoo.com FREE
* @sourcecode 	https://businessbloomer.com/?p=74162
* @author 	Rodolfo Melogli
* @testedwith 	WooCommerce 3.4
*/

add_filter( 'body_class', 'bbloomer_wc_product_cats_css_body_class' );

function bbloomer_wc_product_cats_css_body_class( $classes ){
if( is_tax( 'product_cat' ) ) {
	$cat = get_queried_object();
	if( 0 < $cat->parent  ) $classes[] = 'subcategory';
}
return $classes;
}

Share:

Leave a Reply