How To Override Magento 2.X Theme For A Specific Route?

In this blog, we will see how to override the Magento 2.x theme applied to the store, but only for some specific route(s). It can help to fix faulty layout issues etc. caused due to some third party module which is not compatible with the applied theme.

This can be done by listening to the layout_load_before event and setting the desired theme in the observer, like this:

events.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
	<event name="layout_load_before">
        <observer name="set_theme_for_customroute" instance="ManishJoy\CustomTheme\Observer\SetThemeForMyroute"/>
    </event>
</config>

Observer (SetThemeForMyroute.php)

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace ManishJoy\CustomTheme\Observer;

use Magento\Framework\App\Request\Http;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\DesignInterface;

class SetThemeForMyroute implements ObserverInterface
{
    /** @var Http */
    private $request;

    /** @var DesignInterface  */
    private $design;

    /**
     * @param Http $request
     * @param DesignInterface $design
     */
    public function __construct(
        Http $request,
        DesignInterface $design
    ) {
        $this->request = $request;
        $this->design = $design;
    }

    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer): void
    {
        $actionInfo = $this->request->getFullActionName();

        if ($actionInfo == 'catalog_product_view') {
            $this->design->setDesignTheme('Magento/blank'); /* You need to pass the desired theme name as a param to the setDesignTheme() method like Smartwave/porto, Magento/luma etc. */
        }
    }
}

I hope this blog would help you in the Magento development process. If you need any more help, feel free to contact me.

Updated: