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];
}
}
- run php bin/magento setup:upgrade
Good luck and happy coding !!!