Magento 2: get product collection using category id
-
13-04-2021 - |
Domanda
How to get all products of category using category id in magento 2?
Soluzione
you can inject in your block an instance of \Magento\Catalog\Model\CategoryFactory
like this:
protected $categoryFactory;
public function __construct(
....
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
...
){
...
$this->categoryFactory = $categoryFactory;
...
}
Then create this method in your block:
public function getCategory()
{
$categoryId = $this->getCategoryId();
$category = $this->categoryFactory->create()->load($categoryId);
return $category;
}
public function getProductCollection()
{
return $this->getCategory()->getProductCollection()->addAttributeToSelect('*');
}
Then you can use in the template this:
<?php foreach ($block->getProductCollection() as $product) : ?>
<!-- do something with $product -->
<?php endforeach;?>
You should be able now to just add this to your homepage content
{{block class="Block\Class\Name\Here" category_id="5" template="path/to/template.phtml"}}
Altri suggerimenti
You need to replace getProductsCollection()
by getProductCollection()
(without s
)
I am using this
echo '('.$subcat->getProductCollection()->count().')';
foreach ($subcats as $subcat) {
if ($subcat->getIsActive()) {
$_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
$_imgUrl = $_category->getImageUrl();
$subcat_url = $subcat->getUrl();
// echo $qty = $subcat->getQty(); exit;
$subcat_img = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/category/' . $subcat->getImage();
$placeholder_img = "pub/media/placeholder.png";
if($_imgUrl ==''){
$_imgUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."catalog/category/placeholder.png";
}
?>
<div class="col-sm-2 item-two">
<a href="<?php echo $subcat_url; ?>">
<div class="item-two-img">
<img src="<?php echo $_imgUrl; ?>" class="img-responsive"/>
</div>
<p><?php echo $subcat->getName();
$subcat->getProductCollection()->count(); ?>
<span class="pro_quantity">
<?php echo '('.$subcat->getProductCollection()->count().')';?>
</span>
</p>
</a>
</div>
<?php
}
}
You can use addCategoriesFilter function. With this function you filter by several category ids.
First you need inject CollectionFactory:
protected $_productCollectionFactory;
public function __construct(
....
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
...
){
...
$this->_productCollectionFactory = $productCollectionFactory;
...
}
Then somewhere in the code:
public function getCollectionByCategoryId($id)
{
$ids = [$id];
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => ids]);
return $collection;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange