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.
1 Answer
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
<?php
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
//
$_category=$this->_categoryFactory->create()->load($_categoryID);
$_categoriesFilter = [
'eq' => $_category->getAllChildren(true)
];
$_productCollection = $this->_productCollectionFactory->create();
$_productCollection->addCategoriesFilter($_categoriesFilter);
$_productCollection->addAttributeToSelect('*');
return $_productCollection;
}
}
?>
Template : view\frontent\templates\getallproductsincategory.phtml
<?php
$parentCategoryId = 20;
$productCollection = $block->getProductCollection($parentCategoryId);
?>
<div>
<ol class="row list">
<?php foreach ($productCollection as $product): ?>
<li>
<span><?php echo $product->getSku(). ' - '. $product->getName() ?></span>
</li>
<?php endforeach; ?>
</ol>
</div>
cms static block
{{block class="Gaiterjones\Page\Block\GetAllProductsInCategory" template="Gaiterjones_Page::getallproductsincategory.phtml"}}