Written on 8. October 2020 by Lennart Christensen

How To Get The Primary Category Of Woocommerce product category

Hi, I'm Lennart. WordPress developer from Denmark. I write in Danish, but the piece of code itself is universal and can be understood outside Denmark as well 😀

To retrieve and display the primary category for a product in WooCommerce

There is not a core function in WordPress to display primary category, but if you have installed Yoast SEO plugin, a new function appears in the category that allows you to select the primary category. Given this primary category feature, sometimes we want to retrieve the one primary category, and not just the first one or all of them to which the post or in this case the product is associated.

Then, when we choose more than one category for a product, we get to make one of them primary. Whether or not a post, product, or third entry type should have multiple categories associated with it is another discussion. But often the need arises to restructure a breadcrumb, post meta layout, etc., and we only want to show the primary category.

In this post I've included a feature that shows you how to retrieve only the primary WooCommerce product category for a Product.

In the function a fallback is made. For example, if it cannot find Yoast Seo configured or there is no primary category set for the product, it will take the first category it can find for the individual product. The function can optionally be extended to also give a result if no category is set for the product at all.

You can use the function below to retrieve the main category:

/*--------------------------------------------------------------
Get primary Category @lennartc
--------------------------------------------------------------*/
function getprimcat() {
		$category = wp_get_post_terms( get_the_id(), 'product_cat' );
	$term = false;
	if ( class_exists('WPSEO_Primary_Term') || $category) {
		$wpseo_primary_term = new WPSEO_Primary_Term( 'product_cat', get_the_id() );
		$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
		$term = get_term( $wpseo_primary_term );
		if ($wpseo_primary_term) {
			$term = get_term( $wpseo_primary_term );
			$category_display = $term->name;
		}else {
			$category_display = $category[0]->name;
		}
	}
	return $category_display;
}

To make the code reusable, place the function in your functions.php in your WordPress theme. To output the primary category in the website's frontend, simply use the following:

echo getprimcat()