Adding an is_product_subcategory() Conditional Tag to WooCommerce

wp mayor | is_subcategory

I’ve got a project that needs to treat WooCommerce category pages differently from its subcategory pages. Both use taxonomy-product_cat.php, though. What I’d really love to do is change just the search field in that template, depending on whether a particular page is showing a top-level category or a subcategory.

As it turns out, that’s really easy thanks to the linked article, which walks through adding an is_subcategory() function to your theme or plugin. Clean and simple.

Uh, one thing, though, is that they must have pasted into their code highlighter wrong, so make sure the ->s are actual ->s. There are also some changes to make it ask about product categories rather than product categories.

The full working function for WooCommerce product categories is:

function is_product_subcategory() {
	$cat = get_query_var( 'product_cat' );
	$category = get_term_by( 'slug', $cat, 'product_cat' );
	return ( $category->parent !== 0 );

Thanks to WP Mayor for the start!

Add a comment