0

In Magento 2 I am looking to create a module that adds a custom 404 page specifically for disabled products from Magento Admin.

Can anyone help me how I can proceed to get the desired output?

0

One way to perform such redirect is adding a plugin for \Magento\Cms\Controller\Noroute\Index. Configuration for etc/di.xml for this purpose:

 <type name="Magento\Cms\Controller\Noroute\Index">
        <plugin name="noroute_redirect" 
                type="YourVendor\YourModule\Plugin\Noroute" />
    </type>

And the plugin will look like:

namespace YourModule\YourVendor\Plugin;

class Noroute
{
    private $redirectFactory;

    public function __construct(\Magento\Framework\Controller\Result\RedirectFactory $redirectFactory)
    {
        $this->redirectFactory = $redirectFactory;
    }

    public function aroundExecute(
        \Magento\Cms\Controller\Noroute\Index $index,
        \Closure $proceed
    ) {
        return $this->redirectFactory->create()
                    ->setPath('404notfound');
    }
}

You should also create a CMS Page specifying the 404notfound url-key to handle request to this url. Unfortunately, Magento 2 framework does not allow to save pages with number-only url key. for more

Hope this help you,

0

create a plugin to check the product status "afterGetStatus" method for class \Magento\Catalog\Model\Product,

if the product status is disabled, then create a custom 404 page and forward the controller to that. Find below the code to do that, I have checked it and it is working.

di.xml

<type name="Magento\Catalog\Model\Product">
<plugin name="change_product" type="Rahul\Disabledproductredirect\Plugin\Product" sortOrder="1" />

Plugin/Product.php

namespace Rahul\Disabledproductredirect\Plugin;
use Magento\Framework\Controller\Result\Forward;
use Magento\Framework\App\Request\Http;


    class Product
    {

        private $forward;
        private $request;


        public function __construct(Forward $forward,Http $request)
        {

            $this->forward = $forward;
            $this->request  = $request;
        }

        public function afterGetStatus(\Magento\Catalog\Model\Product $subject, $result)
        {
            //return $result;
            if($result == \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED && $this->request->getControllerName()=='product' && $this->request->getActionName() == 'view')
            {

               $this->forward->forward('noroute');

            }

            return $result;
        }
    }
  • Don't forget to add your custom 404 page identifier instead of "noroute" – Rahul Anand Aug 23 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.