How to Add Category Name of Product as a Class in Body Element

category-productsmagento-2.1PHP

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??

Best Answer

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 !!!

Related Topic