-1

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

4

Try Below Code:

<?php
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');
$store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();

$categoryId = 47; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

$categoryProducts = $category->getProductCollection()
                             ->addAttributeToSelect('*');

foreach ($categoryProducts as $product) 
{
    $imageUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::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

Yatin Khullar
  • 1,580
  • 1
  • 12
  • 26
0

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', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
            ->addFilter('visibility', \Magento\Catalog\Model\Product\Visibility::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="Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\ProductFilterProcessor" type="Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor">
    <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">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductCategoryFilter</item>
            <item name="store" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductStoreFilter</item>
            <item name="store_id" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductStoreFilter</item>
            <item name="website_id" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductWebsiteFilter</item>
        </argument>
    </arguments>
</virtualType>