Fetching Specific Products by ID in Magento 2

Fetching Specific Products by ID in Magento 2

Custom sections such as “staff picks” often need a fixed set of products. In Magento 2 you can load exactly those by filtering a collection on entity IDs.

The code

<?php 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');

foreach ($productCollection as $product) {
           $product_id=$product['entity_id'];
           echo $_product->getName();
}?>

In production code, inject the collection factory rather than calling the object manager, and add visibility and status filters so hidden products never appear.

Need a second pair of eyes on this? Our team handles web development every week. See how we can help.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.