Magento – Magento 2.1 : getLoadedProductCollection() always returns all products

magento-2.1magento2

I am trying to get the collection of visible products on my category page. But as soon as I call getLoadedProductCollection(), my category page shows all products, effectively rendering pagination useless.

My module injects a phtml in the <head>-tag, and it's PHP code is this:

$categoryBlock = $this->getLayout()->getBlock('category.products.list');
$collection = $categoryBlock->getLoadedProductCollection()

Now, if I don't get the loaded products collection, everthing works fine. Magento states 'showing 15 products' and the pagination shows '1-15 of 17'.

However… as soon as my code also wants to have a peek of the product collection by invoking getLoadedProductCollection(), the category page and pagination show all 17 products, even though it's set to a lower value. (It then states 'items 1-17 of 17').

How can I get the same collection as the category page itself? That is: limited by the products that are actually shown?

Best Answer

I know I'm 4 years late but recently I stumbled upon the same issue in Magento 1.9. The key to the problem is that we were trying to insert something related to the product collection inside the <head> tag. Apparently the layer must not be fully initialized by then, and so it doesn't know that the page has the size of 15. By calling the collection in the head we must be overwriting the page size. That's why it shows the full collection in the navigation.

As it wasn't critical for me to have the product collection related computations inside the <head>, I moved it to "before_body_end".

Hopefully I can spare somebody some time with my answer ;)