Magento 2 Redirect disabled product to other URL

create category custom layout in Magento 2

Magento 2 Redirect Disabled Product To Other URL, You can achieve this functionality using override Magento\Cms\Controller\Noroute\Index controller

Create di.xml file
Path: app/code/VenderName/ModuleName/etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Cms\Controller\Noroute\Index" type="VenderName\ModuleName\Rewrite\Controller\Noroute\Index" />
</config>

Create Index.php file
Path: app/code/VenderName/ModuleName/Rewrite/Controller/Noroute/Index.php

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace VenderName\ModuleName\Rewrite\Controller\Noroute;

use Magento\Framework\Controller\Result\ForwardFactory;

use Magento\Framework\App\Response\Http;
use Magento\Framework\App\ResourceConnection;

/**
 * @SuppressWarnings(PHPMD.AllPurposeAction)
 */
class Index extends \Magento\Cms\Controller\Noroute\Index
{
    /**
     * @var ForwardFactory
     */
    protected ForwardFactory $resultForwardFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        Http $redirect,
        ResourceConnection $resourceConnection
    ) {
        $this->resultForwardFactory = $resultForwardFactory;
        $this->request = $request;
        $this->redirect = $redirect;
        $this->resourceConnection = $resourceConnection;
        $this->_storeManager = $storeManager;
        $this->_productloader = $_productloader;
        parent::__construct($context,$resultForwardFactory);
    }

    /**
     * Render CMS 404 Not found page
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {

        $pageId = $this->_objectManager->get(
            \Magento\Framework\App\Config\ScopeConfigInterface::class,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        )->getValue(
            \Magento\Cms\Helper\Page::XML_PATH_NO_ROUTE_PAGE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        // custom code start
        $requestpath =  ltrim($this->request->getPathInfo(), '/');
        $connection  = $this->resourceConnection->getConnection();
        $table       = $connection->getTableName('url_rewrite');
        $id          = $this->_storeManager->getStore()->getId();
        $query       = "SELECT * FROM `" . $table . "` WHERE target_path = '$requestpath' AND entity_type = 'product' AND store_id = '$id' ";        
        $result      = $connection->fetchAll($query);
        
        if($result){
            if(isset($result['0'])){
                if(isset($result['0']['entity_id'])){
                    $productId  =  $result['0']['entity_id'];
                    $product    = $this->_productloader->create()->load($productId);
                  	$myurl  = 'about';
                    return $this->redirect->setRedirect('/'.$myurl);   // redirect to about page        
                    return $this->redirect->setRedirect('/'); // redirect to home                   
                }
            }
        }   
        // custom code end

        /** @var \Magento\Cms\Helper\Page $pageHelper */
        $pageHelper = $this->_objectManager->get(\Magento\Cms\Helper\Page::class);
        $resultPage = $pageHelper->prepareResultPage($this, $pageId);
        if ($resultPage) {
            $resultPage->setStatusHeader(404, '1.1', 'Not Found');
            $resultPage->setHeader('Status', '404 File not found');
            $resultPage->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0', true);
            return $resultPage;
        } else {
            /** @var \Magento\Framework\Controller\Result\Forward $resultForward */
            $resultForward = $this->resultForwardFactory->create();
            $resultForward->setController('index');
            $resultForward->forward('defaultNoRoute');
            return $resultForward;
        }
    }
}

Like us on Facebook and Linkedin for more updates.

Related: Magento 2 Allow Country On Checkout

Back To Top