Skip to content

Instantly share code, notes, and snippets.

@cagartner
Created June 9, 2017 19:39
Show Gist options
  • Save cagartner/70a62c27a554513d0e25aec25e4d6a96 to your computer and use it in GitHub Desktop.
Save cagartner/70a62c27a554513d0e25aec25e4d6a96 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment