:::: MENU ::::

Magento 2 get product categories

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;
     }
Author: Qaisar Satti
Category: Magento 2
Last Modified: December 15, 2017


So, what do you think ?