Question

How can i get latest products programmatically in magento 2?

Was it helpful?

Solution

try this

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToSort('entity_id','desc');
$collection->setPageSize(5); // selecting only 5 products

foreach ($collection as $product) {
    print_r($product->getId());     
    echo "<br>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top