cagartner
6/9/2017 - 7:39 PM

magento 2 add filter by root category

magento 2 add filter by root category

<?php
// ...

    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // If is in other store then default add filter by root category
        if ($this->_storeManager->getStore()->getCode() !== 'default') {
            $rootCategory = $this->_storeManager->getStore()->getRootCategoryId();
            $category = $this->_categoryRepository->get($rootCategory);
            $collection->addCategoriesFilter(['in' => $category->getAllChildren(true, $rootCategory)]);
        }

        $collection->addAttributeToFilter('type_id', 'configurable');
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

        $collection->setPageSize(4);
        return $collection;
    }