Magento – Magento 2 Product Collection with Multi Categories Layered Navigation

layered-navigationmagento2product-collection

I trying to implement custom layered navigation where the users can filter by more than 1 category (not an easy task in M2), I've managed to display all categories and subcategories at all times and filter the products collection with multiple categories.

I've added:
$collection->addCategoriesFilter(array('in' => $categoriesId)); to app\code\Vendor\Module\Model\Layer\Filter\Category.php
but the problem is that it does not affect the toolbar > meaning pagination and product count on page still show results for a single category.

Even when trying to modify the query itself in app\code\Vendor\Module\Model\ResourceModel\Product\Collection.php > _applyProductLimitations it doesn't work.

I'd appreciate any idea or suggestion to solve this problem.

Best Answer

Answering my own question in case you have the same problem:

we need to call $collection->getSize(); after modifying the collection with addCategoriesFilter() function (or any other attributes filtering).

It re-runs the select count query which is used in the Toolbar.php block.