I want to get all the products from Category, and its child categories in magento 2 How can i get that? I have some products assign to main category whereas some assign to child categories. i want to get all product collection.

  • Where you want to use this one? Commented May 9, 2020 at 13:14

1 Answer 1


Here is one way to do this using a custom module, in this case I used my Page module with a new Block and Template. I called it from a static block in cms.

Parent category is specified in the template. The product collection returns all products in parent and child categories.

Block : Gaiterjones\Page\Block\GetAllProductsInCategory

namespace Gaiterjones\Page\Block;

use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;

class GetAllProductsInCategory extends \Magento\Framework\View\Element\Template
        protected $_categoryFactory;
        protected $_productCollectionFactory;

    public function __construct(
        Context $context,
        CategoryFactory $categoryFactory,
        ProductCollectionFactory $productCollectionFactory,
        array $data = []
        $this->_categoryFactory = $categoryFactory;
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);

    public function _prepareLayout()
        return parent::_prepareLayout();

    public function getAllCategoryProducts($_categoryID)
        return $this->getProductCollection($_categoryID);

    public function getProductCollection($_categoryID)
        // get products in category and all child categories
        $_categoriesFilter = [
            'eq' => $_category->getAllChildren(true)

        $_productCollection = $this->_productCollectionFactory->create();

        return $_productCollection;


Template : view\frontent\templates\getallproductsincategory.phtml

$parentCategoryId = 20;
$productCollection = $block->getProductCollection($parentCategoryId);

    <ol class="row list">
        <?php foreach ($productCollection as $product): ?>
                <span><?php echo $product->getSku(). ' - '. $product->getName() ?></span>
        <?php endforeach; ?>

cms static block

{{block class="Gaiterjones\Page\Block\GetAllProductsInCategory" template="Gaiterjones_Page::getallproductsincategory.phtml"}}
  • This worked for me. thank you
    – Nafsss
    Commented May 11, 2020 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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