Get Product Collection with a Specific Attributes in Magento 2
In this article we'll discuss how to get product collection with a specific attribute in magento 2. We'll get collection in a block file.
Check the following code to get specific attribute collection.
saveCopyzoom_out_mapnamespace Devhooks\Module\Block;
class Module extends \Magento\Framework\View\Element\Template
{
protected $productFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,
array $data = []
)
{
$this->productFactory = $productFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productFactory->create();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');
return $collection;
}
}
In above code I have add name and price attribute. So, we'll get that with collection. But, incase if you want to get all attribute with collection then replace below code with above.
saveCopyzoom_out_mappublic function getProductCollection()
{
$collection = $this->productFactory->create();
$collection->addAttributeToSelect('*');
return $collection;
}
Now, we'll print the product collection in .phtml file. Check following code to get product collection in phtml file. In this code we just call getProductCollection method from our block.
saveCopyzoom_out_map$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { echo "<pre>"; print_r($product->getData()); echo "</pre>"; }
Finally, we are done, let's flush or refresh cache and test the result.
That’s it.
I hope this post helped you to find what you were looking for. Bookmark it for your future reference. Do comment below if you have any other questions on that.
P.S. Do share this note with your team.
AI-Powered Recommended Articles
How to Get Product Collection in Magento 2
Learn how to get product collections in Magento 2 and filter them based on various parameters.
Magento 2 Get Product Collection By Cetegory ID
Learn how to retrieve a product collection by category ID in Magento 2 for customized product listings and filters.
Magento 2 Get Product Collection with Filters
Learn how to get a product collection in Magento 2 with custom filters for enhanced product retrieval and display.
How to Get Current Product in Magento 2
Learn how to retrieve the current product in Magento 2 to dynamically display product-specific information on your website.
How to Get Current Category in Magento 2
Learn how to retrieve the current category in Magento 2 using code to display relevant category data in your store.
How to Get Salable Quantity in Magento 2
Learn how to retrieve the salable quantity of a product in Magento 2 to ensure accurate inventory tracking and display on your site.