1

I have single product page on my site. The product is having category "beauty".

Product display page having following body tag:

<body data-container="body" class="catalog-product-view product-extra-firming-night">

body tag have classes -: catalog-product-view product-extra-firming-night

Now what I want? I want to add/insert additional class in body tag. (see body tag below).

<body data-container="body" class="catalog-product-view product-extra-firming-night current-category-beauty">

My workaround is as follows:

I have checked the code in following file. Check the if condition.

[https://github.com/magento/magento2/blob/2.1-develop/app/code/Magento/Catalog/Helper/Product/View.php#L162][1]

Also tried to add custom code above if condition.

$pageConfig->addBodyClass('product-' . $product->getCategory());

Can anybody help on this issue. how to add category name as a class in body tag??

2 Answers 2

2

you can follow these steps :

1.Create your own module ( example :Vendor/Mysample)

2.app/code/Vendor/Mysample/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Vendor_Mysample" setup_version="1.0.0" />
</config>

3.Create file under app/code/Vendor/Mysample/etc/frontend/di.xml and copy this code :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">


<type name="Magento\Framework\View\Result\Page">
<plugin name="mySampleResultPage" type="Vendor\Mysample\Plugin\Result\Page"/>
</type>

</config>

4.Create the registration file app/code/Vendor/Mysample/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Mysample',
__DIR__
);

5.Create the file app/code/Vendor/Mysample/Plugin/Result/Page.php and copy the below code :

<?php
namespace Vendor\Mysample\Plugin\Result;

use Magento\Framework\App\ResponseInterface;

class Page
{
  private $context;
  private $registry;

  public function __construct(
  \Magento\Framework\View\Element\Context $context,
  \Magento\Framework\Registry $registry
  ) {
     $this->context = $context;
     $this->registry = $registry;
  }

  public function beforeRenderResult(
  \Magento\Framework\View\Result\Page $subject,
  ResponseInterface $response
  ){

  $category = $this->registry->registry('current_category');

  if($this->context->getRequest()->getFullActionName() == 'catalog_product_view'){
     $subject->getConfig()->addBodyClass('current-category-'.$category->getName());
  }

  return [$response];
  }
}
  1. run php bin/magento setup:upgrade

Good luck and happy coding !!!

11
  • Sami, I will try this solution and will let u know.....
    – 1990rk4
    Commented Aug 15, 2018 at 13:27
  • @rk1990 , i tested it and it works ;) . Instead of Vendor/Mysample , you can choose the naming like you want
    – sami23
    Commented Aug 15, 2018 at 13:35
  • ok ... i will try this ...
    – 1990rk4
    Commented Aug 15, 2018 at 13:37
  • 1
    Hi sami, thanks, this working for me ... But, the only issue is when i click on product under root category then it gives error "unable to handle request" .. For e,g I have root category "Beauty". When i click on product listed under "Beauty" it gives me error. but when I click on product under "Beauty -> Skincare" it works for me... any suggetion??
    – 1990rk4
    Commented Aug 16, 2018 at 6:51
  • @rk1990 can you give more details eg pic to can reproduce the error
    – sami23
    Commented Aug 16, 2018 at 8:40
0

We can use event layout_load_before to add css class based on current category.

app/code/Vendor/Module/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="Innoppl_Test" instance="Vendor\Module\Observer\Bodycss" shared="false" />
    </event>
</config>

app/code/Vendor/Module/Observer/Bodycss.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\View\Page\Config;
use Magento\Store\Model\StoreManagerInterface;

class Bodycss implements ObserverInterface
{
    protected $config;
    protected $storeManager;
    protected $request;
    protected $categoryRepository;

    public function __construct(
        Config $config,
        StoreManagerInterface $storeManager,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
    ){
        $this->config = $config;
        $this->storeManager = $storeManager;
        $this->request = $request;
        $this->categoryRepository = $categoryRepository;
    }

    public function execute(Observer $observer){
        $controller = $this->request->getControllerName();
        $action     = $this->request->getActionName();
        $route      = $this->request->getRouteName();
//      check - is this category page
        if($route == "catalog" && $controller == "category" && $action == "view")
        {
            $category = $this->categoryRepository->get($this->request->getParam("id"));
            $this->config->addBodyClass("current-category".$category->getName());
        }        

    }

}  

I have tested, it works Easy for your reference

3
  • Bilal, app/code/Vendor/Module/etc/frontend/events.xml.. means you are saying to create custom extension? or should I change code in file, app/code/Magento/Catalog/etc/frontend/events.xml and create new php file under app/code/Magento/Catalog/observer... please guide....
    – 1990rk4
    Commented Aug 15, 2018 at 13:26
  • I am new to magento... so i am little bit confused with file name you mentioned above... it your answer demands to create new extension or should i change code in existing file... Bodycss.php is custom file???? please guide...
    – 1990rk4
    Commented Aug 15, 2018 at 13:30
  • Thanks, Bilal, this is works for me ... but only on category page.. I want to display category name also on single product page... Can you please help?
    – 1990rk4
    Commented Aug 16, 2018 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.