Magento – Magento 2: Sort order and limit product collection

magento2product-collection

I need to sort the product collection by ID order DESC and add limit to product collection. Here is my code:

$objectManager     = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection        = $productCollection->create()
    ->addAttributeToSelect('*')
    ->load();

Best Answer

Just add this code addAttributeToSort('entity_id', 'desc') to your collection.

As product follows EAV structure, you can use addAttributeToSort('attribute_code', 'sort_order')

For limiting a collection use setPageSize() and setCurPage() methods:

$collection = $productCollection->create()
    ->addAttributeToSelect('*');

$collection 
    ->setPageSize(10) // only get 10 products 
    ->setCurPage(1)  // first page (means limit 0,10)
    ->load();