WooCommerce: Get Product Parent Categories

Whenever we need to do custom WooCommerce work, remembering how to get “things” is the most time-consuming task. So, a Google search often helps us find the right and quickest solution.

For example, it’s easy to “get the current product’s categories“, but how can we get the “parent product categories” only? In today’s snippet we will see how this can be achieved in 7 lines of PHP. Enjoy!

In this example, the code below would return the IDs of “Business Bloomer Club” and “Clothing” product categories only.

PHP Snippet: Get Current Product’s Parent Categories @ Single Product Page

The PHP below fills the $parent_categories array with parent product category IDs.

/**
 * @snippet       Get Parent Categories @ WooCommerce Single Product
 * @how-to        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

$categories = get_the_terms( get_the_ID(), 'product_cat' );
$parent_categories = array();
foreach ( $categories as $category ) {
	if ( $category->parent == 0 ) {
		$parent_categories[] = $category->term_id;
	}
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *