Magento 2 get product categories

In our daily coding routine you have to work with product and category. So today we learn how to get Magento 2 product categories from product object.You can always get the assigned categories of a product using following code.

In Constructor:

protected $_productFactory;
public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->_productFactory = $productFactory;
    }
    public function getProductCategories()
    {
      $product = $this->_productFactory->create()->load($pid); // $pid = Product_ID

      return  $product->getCategoryIds();
     }

Now we get all categories from product collection.

protected $_productCollectionFactory;
protected $_productloader;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,
         \Magento\Catalog\Model\ProductFactory $productloader
    ) {
        $this->_productCollectionFactory = $productFactory;
        $this->_productloader = $productloader;
    }
    public function getProductCollectionCategories()
    {
      $prodIds= $this->_productCollectionFactory->create(); // $pid = Product_ID
      foreach($prodIds as $pid){          
         $product = $this->_productloader->create()->load($pid);  
         $proCats = $product->getCategoryIds();    
         $catIds= array_merge($catIds, $pproCats);  
       }
      $finalCat = array_unique($catIds);
      return  $finalCat;
     }

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply