Magento 1 – Show Different Number of Products in Category Page

categorycollection-limitmagento-1paginationproduct-collection

I am trying to show different number of products in category but it is only working on page 1. I want to show 22 products on page1 and rest all the pages 20 products per page. I managed to change by setPageSize in first page and it is working well, but rest all the pages I am unable to get products limit to 20 per page.

Page 1...22 products //works well
Page 2...20 products //doesn't work..shows from 21 to 40
Page 3...20 products //doesn't work..shows from 41 to 60

Here is how I am doing:

$currentPage = (int) Mage::app()->getRequest()->getParam('p');
if ($currentPage==0 || $currentPage==1){
    $productCollection->clear();
    $productCollection->setCurPage($currentPage)->setPageSize(22); //works..
} else {
        $productCollection->clear(); 
        $productCollection->getSelect()->limit(20,22); //doesn't work
}

Any idea how can I solve this?

Thanks.

Best Answer

The problem is that the LIMIT is calculated based on "page size" and "current page" immediately before the collection is loaded. See Mage_Eav_Model_Entity_Collection_Abstract::_loadEntities():

public function _loadEntities($printQuery = false, $logQuery = false)
{
    if ($this->_pageSize) {
        $this->getSelect()->limitPage($this->getCurPage(), $this->_pageSize);
    }

You can prevent this by setting _pageSize to 0:

$productCollection->setPageSize(0);
$productCollection->getSelect()->limit(20,22);

Besides that, resetting the already loaded collection to load it again is not a good idea.

You can write an observer for catalog_product_collection_load_before to manipulate the limit right before the collection is loaded:

public function setProductPaging(Varien_Event_Observer $observer) 
{
    $collection = $observer->getCollection();
    if ($collection->getCurPage() == 1) {
        $collection->setPageSize(22);
    } else {
        $productCollection->setPageSize(0);
        $productCollection->getSelect()->limit(20, 22 + 20 * ($collection->getCurPage() - 2));
    }
}