Magento – How to retrieve which layered navigation filters are applied in product list page in Magento 2

blockslayered-navigationmagento-2.1magento2product-list

I'm going to write a block to put in products list page. My question is how can I get to know which layered navigation filters are currently applied in the current list page ?

Any help will be appreciated.

Best Answer

You can do this with the layer resolver (Magento\Catalog\Model\Layer\Resolver). Example code:

public function __construct(
    \Magento\Catalog\Model\Layer\Resolver $layerResolver
)
{
    $this->layerResolver = $layerResolver;
    $layer = $this->layerResolver->get();
    $activeFilters = $layer->getState()->getFilters();
}

Edit:

A small sidenote to those who might concern: you can only get the state after \Magento\Catalog\Controller\Category\View::execute() has already created the state. Otherwise you get a Catalog Layer has been already created runtime exception.