skip to Main Content

I am working in Magento 2.2.1, I am trying to get product-collection of a category by its category id.

Every time when i use to call using this example, I always get an error.

2

Answers


  1. Try Below Code:

    <?php
    $objectManager =  MagentoFrameworkAppObjectManager::getInstance();        
    
    $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
    $categoryHelper = $objectManager->get('MagentoCatalogHelperCategory');
    $categoryRepository = $objectManager->get('MagentoCatalogModelCategoryRepository');
    $store = $objectManager->get('MagentoStoreModelStoreManagerInterface')->getStore();
    
    $categoryId = 47; // YOUR CATEGORY ID
    $category = $categoryFactory->create()->load($categoryId);
    
    $categoryProducts = $category->getProductCollection()
                                 ->addAttributeToSelect('*');
    
    foreach ($categoryProducts as $product) 
    {
        $imageUrl = $store->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();
        ?>
    
         <div class="product-container">
                      <a href="<?= $product->getProductUrl(); ?>">
    
                         <div class="new-arrivals-image"><img src="<?= $imageUrl;?>"></div>
                         <div class="product-name"><span class="name"><?= $product->getName(); ?></span></div>
                      </a>
                      <div class="price"><span class="pt"><?= $product->getPrice(); ?></span></div>
                   </div>
    
    <?php
    }
    ?>
    

    I hope it will help you

    Login or Signup to reply.
  2. Better and more actual way to get products by category – via ProductRepository and built-in Filters (from Magento 2.2)

    public function __construct(
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilder $criteriaBuilder
    ) {
        $this->productRepository = $productRepository;
        $this->criteriaBuilder = $criteriaBuilder;
    }
    
    /**
     * @return ProductInterface[]
     */
    public function getProducts(): array
    {
        $categoryIdsToExport = $this->config->getCategoriesToExport();
    
        return $this->productRepository->getList(
            $this->criteriaBuilder
                //It's Custom Filter from di.xml
                ->addFilter('category_id', $categoryIdsToExport, 'in') 
                //Here you cat filter products in standart Magento way
                ->addFilter('status', MagentoCatalogModelProductAttributeSourceStatus::STATUS_ENABLED)
                ->addFilter('visibility', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH)
                ->create()
        )->getItems();
    }
    

    Unfortunately There are few info in stackexchange about "Search Criteria Unify Processing" – better and currently proper way to filter,sort models.

    Here Magento doc about Search Criteria Unify Processing

    Also you can register your own CustomFilter to filter products.
    See example in vendor/magento/module-catalog/etc/di.xml :

    <virtualType name="MagentoCatalogModelApiSearchCriteriaCollectionProcessorProductFilterProcessor" type="MagentoEavModelApiSearchCriteriaCollectionProcessorFilterProcessor">
        <arguments>
            <argument name="customFilters" xsi:type="array">
                <!-- You can specify your attribute and map a class to apply filter -->
                <item name="category_id" xsi:type="object">MagentoCatalogModelApiSearchCriteriaCollectionProcessorFilterProcessorProductCategoryFilter</item>
                <item name="store" xsi:type="object">MagentoCatalogModelApiSearchCriteriaCollectionProcessorFilterProcessorProductStoreFilter</item>
                <item name="store_id" xsi:type="object">MagentoCatalogModelApiSearchCriteriaCollectionProcessorFilterProcessorProductStoreFilter</item>
                <item name="website_id" xsi:type="object">MagentoCatalogModelApiSearchCriteriaCollectionProcessorFilterProcessorProductWebsiteFilter</item>
            </argument>
        </arguments>
    </virtualType>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search