You can do this using a plugin:
Create the file app/code/Myvendor/Mymodule/etc/frontend/di.xml with the following content:
<?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="myModuleResultPage" type="Myvendor\Mymodule\Plugin\Result\Page"/>
</type>
</config>
Create the file app/code/Myvendor/Mymodule/Plugin/Result/Page.php with the following content:
<?php
namespace Myvendor\Mymodule\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_category_view'
&& $category
&& $category->getId() == <some_category_id>){
$subject->getConfig()->addBodyClass('my_custom_class');
}
return [$response];
}
}
Replace the "some_category_id" with the category id that you want to add the custom body class in.
Note: In order to this solution to work, you need a working plugin "Myvendor_Mymodule", if you don't have the plugin, just do the following to create it:
Create the following file -
app/code/Myvendor/Mymodule/etc/module.xml
With the following content
<?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="Myvendor_Mymodule" setup_version="1.0.0" />
</config>
And the following file - app/code/Myvendor/Mymodule/registration.php
with the following content -
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Myvendor_Mymodule',
__DIR__
);
Reference: https://www.mexbs.com/magento-blog/adding-custom-body-class-magento2/