I am working on a custom script (not custom module) where I need to fetch product collection and display 5 products at a time. After displaying 5 products there is a link Next which displays next 5 records and so on.

How can i do this. Please.

2 Answers 2



//your code goes here...
$page_number =  $_GET['p'];

/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollection = $productCollectionFactory->create()

foreach ($productCollection as $p){
    echo $p->getName().'<br>';


echo "<a href='?p=$page_number'>Next</a>";
  • use of object manager is no more recommended. Nov 16, 2022 at 11:32
  • I was doing a custom script, not a module. How else we can create objects? Can you please suggest @Oscprofessionals?
    – Abid Malik
    Dec 14, 2022 at 4:16

protected $_productCollectionFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);

public function getProductCollection() { $collection = $this->_productCollectionFactory->create(); $collection->addAttributeToSelect('*'); ->setPageSize(5) ->setCurPage($page_number) // you need to get page number ->load();

    return $collection;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.