Magento – Magento2: How to get total page number of category

magento2paginationproduct-collection

I want to show Title of category page based current page and total page.
for example: Category Electronics has total 20 page and i am on 2nd page. I want to show 2 out of 20 pages.

I have tried below code.

 $current_page =  $this->request->getParam("p");

 $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
            $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');

            $categoryId = $this->request->getParam("id"); // YOUR CATEGORY ID
            $category = $categoryFactory->create()->load($categoryId);


            $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
            $collection = $productCollectionFactory->create();

            $collection->addAttributeToSelect('*');
            $collection->addCategoryFilter($category);
            $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
            $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
            $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);


echo $current_page." of "ceil(count($collection)/48);

I have limiter value 48. But i am getting different count of product than actual showing in category page.

Best Answer

You need to set page limit and page number in collection. Try following way:


$collection->setCurPage($current_page)->setPageSize(9);
echo $current_page." of ".$collection->getLastPageNumber();

Following line return last page number. For example: you have 10 page then it return 10.

$collection->getLastPageNumber()