Woocommerce – testing if a product is in a descendent category

To test whether a WordPress post is within a particular category or any of its subcategories, there’s a handy snippet in the WordPress codex here: http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category

For WordPress noobs like me (and what environment has more noobs than WordPress?), though, it’s not obvious how to make that work for Woocommerce product categories. There are two key things you need to know:

  1. Woocommerce product categories do not use the normal category system. They use a custom taxonomy called ‘product_cat’
  2. The in_category function used in that snippet only works with the normal categories. For custom taxonomies, you have to use has_term() instead.

The revised snippet looks like this:

if ( ! function_exists( 'post_is_in_descendant_product_cat' ) ) {
	function post_is_in_descendant_product_cat( $cats, $_post = null ) {
		foreach ( (array) $cats as $cat ) {
			// get_term_children() accepts integer ID only
			$descendants = get_term_children( (int) $cat, 'product_cat' );
			if ( $descendants && has_term($descendants, 'product_cat', $_post) )
				return true;
		return false;