Home » Magento, Magento 21 March 2016

Magento 2: Get all Products of a Category

This article shows how we can get all products of a particular category in Magento 2.

Both Dependency Injection and Object Manager way of coding is shown below.

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\CategoryFactory class in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php

Now, we get products in a particular category and then print the product collection in our template (.phtml) file.

Using Object Manager

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Ali

    Hi Mukesh,
    Excellent blog post. That’s exactly what I’m trying to do.
    I’ve copied your code but unfortunately it’s still not working for me.
    I don’t know if I missed something. But when I just echo a message before $category = $this->_categoryFactory->create(); The message is correctly displayed. When I put it after, I get an error.
    Thanks

  • Ali

    Sorry Mukesh, it’s working perfect. I had a memory exhausted caused by a var_dump :).
    Thanks

  • jBOKA

    Hi Mukesh,
    I have a category (id 2) holding a subcategory (id 4) holding four products.
    Do you have any idea, why I get these four products with your code when loading the productcollection of category (id 2), but when I do exactly the same for subcategory (id 4), the product collection is empty.
    Maybe I’m missing something obvious. I emptied cache and reindexed.
    Regards

  • jBOKA

    Turns out Mage2 has some serious problems with multiple categories directly under root. I can’t reproduce, but it’s working now. Don’t ask me… :)

  • Gurinder Sason

    Hi mukesh,

    It works for me too, but i want some other details of product too in this as product image, price etc. but when i use $block->getImage($_product, $image)

    in block file to get images. it is returning null. please help how i can get images of product collection by category.

    thanks