// Load the Magento 2 Category model use Magento\Catalog\Model\Category; // Get the category ID of a specific category $categoryID = 123; // Load the category model $category = $this->_objectManager->create(Category::class)->load($categoryID); // Retrieve the top-level category ID $topCategoryID = $category->getTopCategory()->getId();
// Load the WooCommerce category model use WC_Product_Catgeory; // Get the category ID of a specific category $categoryID = 123; // Load the category model $category = new WC_Product_Category($categoryID); // Retrieve the top-level category ID $topCategoryID = $category->get_top_category_id();In this example, we are using WooCommerce's Product Category model to load a specific category and then retrieve its top-level category ID using the get_top_category_id() function. Package/Library: WooCommerce\Product\Category