1

Can anyone see what I am doing wrong here. It displays All categories instead of only showing the specific website/store categories.

$collection = $this->_categoryCollectionFactory->create();

$collection->addAttributeToFilter('featured_category', 1)
        ->addFieldToFilter('is_active', 1)
        ->addAttributeToSort('featured_sortorder')
        ->addAttributeToSelect('*');

$collection->setStore($this->_storeManager->getStore());

Update:

I got it working by adding a path filter. It now shows the categories by website/store.

/**
 * Retrieve featured categories
 * 
 * @return \Magento\Catalog\Model\ResourceModel\Category\Collection
 * @throws \Magento\Framework\Exception\LocalizedException
 * @throws \Magento\Framework\Exception\NoSuchEntityException
 */
public function getFeaturedCategories()
{
    $rootCategoryId = $this->_storeManager->getStore()->getRootCategoryId();
    
    $collection = $this->_categoryCollectionFactory->create();
    $collection->addIsActiveFilter()
        ->addAttributeToFilter('path', array('like' => "1/{$rootCategoryId}/%"))
        ->addAttributeToFilter('featured_category', 1)
        ->addAttributeToSort('featured_sortorder')
        ->addAttributeToSelect('*');
    return $collection->load();
}
3
  • call $collection->load() after applying everything – Philipp Sander Jun 16 '20 at 12:55
  • Unfortunately adding ->load() did not work. Also, ->getId() did not work either @Ashish Raj – Paul Donnelly Jun 16 '20 at 14:00
  • Thanks for your help. I managed to get it working. I've updated my answer. – Paul Donnelly Jun 16 '20 at 14:34
0

Your collection is correct, just need to add ->getId() function after $this->_storeManager->getStore(). As the category collection setStore function support storeId not store object.

$collection = $this->_categoryCollectionFactory->create();

$collection->addAttributeToFilter('featured_category', 1)
        ->addFieldToFilter('is_active', 1)
        ->addAttributeToSort('featured_sortorder')
        ->addAttributeToSelect('*');

$collection->setStore($this->_storeManager->getStore()->getId());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.