Get variation categories in WooCommerce with PHP

/**
 * Gets variation (or product) categories.
 *
 * @see https://wpcodebook.com/get-variation-categories-woocommerce-php/
 * @see https://woocommerce.github.io/code-reference/classes/WC-Product.html
 */
function wpcodebook_get_product_or_variation_category_ids( $product ) {

	$category_ids = $product->get_category_ids();

	if (
		empty( $category_ids ) &&
		0 != ( $parent_id = $product->get_parent_id() ) &&
		( $parent_product = wc_get_product( $parent_id ) )
	) {
		$category_ids = $parent_product->get_category_ids();
	}

	return $category_ids;
}

Leave a Comment