I want to filter category by store id. Used the following code, but it is not working.
$collection = $this->categoryCollectionFactory->create(); $collection->addAttributeToSelect('*') ->setStoreId(0);
$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect('*')
->setStore($storeId);
instead ->setStoreId(0); use ->setStore(0);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryCollection->create();
$categories->addAttributeToSelect('*');
$categories->setStore('0'); /* set here your store id */
foreach ($categories as $category) {
echo $category->getName() . '<br />';
}
Pretty valid question with no valid answers so far. Hopefully my answer will help you to solve the issue. In fact, "setStore" or "setStoreId" did nothing for me, still current store ID was used.
Here's a workaround for this that I've found as the easiest:
$currentStoreId = $this->storeManager->getStore()->getId();
$this->storeManager->setCurrentStore(2);
$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect('name');
$cats = $collection->getColumnValues('name');
// Don't forget to bring back the initial store ID
$this->storeManager->setCurrentStore($currentStoreId);
Try below code. this is working for me.
$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($this->_storeManager->getStore($store_id));