I have a category with some subcategories:
- Lamps
-- Hanging lamps
-- Wall lamps
-- Floor lamps
When clicking on one of the three subcategories in the Layered Navigation, the product listing is filtered to the products of that specific category. I don't want it to filter, but I want the subcategories in the Layered Navigation to actually link to the category.
Is this a Magento 2 setting, or does this require custom changes? If so, can anybody help me get started? I've done some searching, but was only able to find a similar question for Magento 1.
You need to use a custom plugin class. Where you can change the core behavior of getUrl
method in Magento\Catalog\Model\Layer\Filter\Item
class. Because this getUrl
method is responsible for generating all filter URLs.
app/code/Vendor/Module/etc/di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Layer\Filter\Item">
<plugin disabled="false" name="Vendor_Module_Plugin_Magento_Catalog_Model_Layer_Filter_Item" sortOrder="10" type="Vendor\Module\Plugin\Magento\Catalog\Model\Layer\Filter\Item"/>
</type>
</config>
app/code/Vendor/Module/Plugin/Magento/Catalog/Model/Layer/Filter/Item.php
<?php
namespace Vendor\Module\Plugin\Magento\Catalog\Model\Layer\Filter;
class Item
{
protected $categoryHelper;
protected $categoryRepository;
public function __construct(
\Magento\Catalog\Helper\Category $categoryHelper,
\Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
$this->categoryHelper = $categoryHelper;
$this->categoryRepository = $categoryRepository;
}
public function afterGetUrl(
\Magento\Catalog\Model\Layer\Filter\Item $subject,
$result
) {
// custom url for category filter
if ($subject->getFilter()->getRequestVar() == 'cat') {
$categoryId = $subject->getValue();
$categoryObj = $this->categoryRepository->get($categoryId);
return $this->categoryHelper->getCategoryUrl($categoryObj);
}
return $result;
}
}
Here after
plugin method (afterGetUrl
) is used. Which runs after the main method (getUrl
).
If you want to know more about plugin class. You can check here.