I have number of subcategories under a main category called 'services'. I want to add a custom class 'service-listing' to body on all the subcategory pages under this category.
1 Answer
I once did it with an observer.
First declare it in Namespace/ModuleName/etc/frontend/events.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_load_before">
<observer name="namespace_modulename_load_layout" instance="Namespace\ModuleName\Observer\LoadLayout" />
</event>
</config>
Then create the file in app/code/Namespace/ModuleName/Observer/LoadLayout.php
namespace Namespace\ModuleName\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Page\Config;
class LoadLayout implements ObserverInterface
{
public function __construct(
Config $pageConfig,
\Magento\Framework\Registry $registry
) {
$this->_pageConfig = $pageConfig;
$this->_registry = $registry;
}
/**
* @param Observer $observer
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$parentCategoryId = $this->getLevel1Category();
if($parentCategoryId=='your specific category id'){
$this->_pageConfig->addBodyClass('your wanted body class');
}
return $this;
}
public function getLevel1Category(){
if($this->getCurrentCategory()){
if($this->getCurrentCategory()->getParentCategories()){
foreach ($this->getCurrentCategory()->getParentCategories() as $parent) {
if ($parent->getLevel() == 2) { //the level could be different depending on your category architecture
return $parent->getId();
}
}
}
}
return null;
}
private function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
}
The part to retrieve the category ID was based on this : Magento 2 How to get first level parent category of current Category?