Get Category collection from product ID in Magento 2

Magento method of fetching Category IDs



// Get a product Data Model from the repository:
$product = $this->productRepository->getById($productId);

// Fetch the 'category_ids' attribute from the Data Model.
if ($categoryIds = $product->getCustomAttribute('category_ids')) {
    foreach ($categoryIds->getValue() as $categoryId) {
        $category = $this->categoryRepository->get($categoryId);
    }
}
If you are on a product page/phtml, get product ids through below method:

   $product_categories = $_product->getCategoryIds();

It will be in form of array data.



No comments:

Post a Comment

Buy/Sell Source Code of Website,Apps,Softwares

Install sample data in magento 2