Just to confirm, I've tested your code on a fresh Magento 2.1.2 and it works absolutely fine in both cases (when accessing the product via its direct URL or when accessing the product via the category).
Regarding your second question: yes I'm 90% sure the Porto theme is the problem. All those themes are shipped with a huge number of widgets, modules, custom modifications which are very often the root cause of many issues.
I'm not saying those themes are bad, they're great when you're dealing with a small store which do not need a lot of custom development and modifications. However, when you're dealing with a bigger structure, problems arise.
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 !!!
Best Answer
Use following code it may be helps use