Here’s the step-by-step process to change the product page layout in Magento 2.
Step #1
First of all, we will have to create a di.xml file to add the plugin in app/code/Gohil/Rajesh/etc/frontend/
directory and add the following code into the file.
<?xml version="1.0"?>
<!--
/**
* Created By : Gohil Rajesh
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Controller\Product\View">
<plugin name="Gohil_Rajesh::change_product_view" type="Gohil\Rajesh\Plugin\Catalog\Controller\Product\View" sortOrder="1" />
</type>
</config>
Step #2
Next, we will also have to create a View.php file for the plugin in the app/code/Gohil/Rajesh/Plugin/Catalog/Controller/Product/ directory and copy the following code in the file.
<?php
/**
* Created By : Gohil Rajesh
*/
namespace Gohil\Rajesh\Plugin\Catalog\Controller\Product;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
class View
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @param RequestInterface $request
* @param ProductRepositoryInterface $productRepository
* @param StoreManagerInterface $storeManager
*/
public function __construct(
RequestInterface $request,
ProductRepositoryInterface $productRepository,
StoreManagerInterface $storeManager
) {
$this->request = $request;
$this->productRepository = $productRepository;
$this->storeManager = $storeManager;
}
public function afterExecute(\Magento\Catalog\Controller\Product\View $subject, $resultPage)
{
if ($resultPage instanceof ResultInterface)
{
$productId = (int) $this->request->getParam('id');
if ($productId)
{
try
{
$product = $this->productRepository->getById($productId, false, $this->storeManager->getStore()->getId());
if (Your Condition)
{
$pageConfig = $resultPage->getConfig();
$pageConfig->setPageLayout('2columns-right'); //Set your page layout here.
}
}
catch (NoSuchEntityException $e)
{
// Add you exception message here.
}
}
}
return $resultPage;
}
}
In the above plugin file, you’ll need to set your desired layout in the setPageLayout().
But in our example, we will set the product page layout to be displayed 2 columns-right if condition is true
So, once you set your desired layout, the last thing you need to do is clean the cache and check the output.