0

is there a way we can redirect a product if the product is out of stock, then redirect that product to its assigned category page (if multiple categories assigned then redirect to the first category assigned) ?

1
  • Any thoughts on this ?
    – user104369
    Commented Dec 1, 2022 at 9:41

4 Answers 4

2

Why would you want to?

If you redirect and a Search Bot picks up that redirect, they'll drop the initial URL - then when it comes back into stock, they'll never reindex that URL.

Much safer to show an "Out of stock" message and maybe a link to other in stock products.

[EDIT]

I'm amazed at how many people (below) have worked to find a solution to this problem without taking into consideration the effects of actually doing this. Just because you can, doesn't mean you should.

Just let it show out of stock, or at worst a 404. Anything else is damaging the site's rep.

Only time you should be redirecting a PDP is if the product is discontinued, and even then, where would you redirect it? All your relevance is for that product so maybe redirect to a category... but that's a poor user experience.

The best UX would be to mark as out of stock and show alternatives.

0
1

You can achieve this functionality by following below code.

I have used plugin for this functionality.

Please follow below steps.

Step 1:-

Define plugin in Vendor/Module/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">
    <type name="Magento\Catalog\Controller\Product\View">
        <plugin name="redirect_product_if_out_of_stock"  type="Vendor\Module\Plugin\ProductRedirectPlugin" />
    </type>
</config> 

Step 2:-

Create Plugin class and define logic in it. Vendor/Module/Plugin/ProductRedirectPlugin.php

  <?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Plugin;

use Magento\CatalogInventory\Model\Stock\Item;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Catalog\Model\ProductCategoryList;

class ProductRedirectPlugin
{
    protected $_stockItem;
    protected $_storeManager;
    protected $_categoryRepository;
    protected $_response;
    protected $_productCategory;


    public function __construct(
        Item $stockItem,
        CategoryRepositoryInterface $categoryRepository,
        StoreManagerInterface $storeManager,
        ResponseInterface $response,
        ProductCategoryList $productCategory
    )
    {
        $this->_stockItem = $stockItem;
        $this->_categoryRepository = $categoryRepository;
        $this->_storeManager = $storeManager;
        $this->_response = $response;
        $this->_productCategory = $productCategory;
    }

    public function beforeExecute(\Magento\Catalog\Controller\Product\View $subject)
    {
        // Get initial data from request
        $categoryId = "";
        $productId = (int) $subject->getRequest()->getParam('id');

        try {
            $stockItem = $this->_stockItem->load($productId, 'product_id');
            if (!$stockItem->getIsInStock()) {
                $categoryIds = $this->_productCategory->getCategoryIds($productId);
                if (!empty($categoryIds)) {
                    $categoryId = array_unique($categoryIds)[0];
                    $category = $this->_categoryRepository->get($categoryId, $this->_storeManager->getStore()->getId());
                    $this->_response->setRedirect($category->getUrl(), 301)->sendResponse();
                }
            }
        } catch (\Exception $e) {
            // HANDLE EXCEPTION BASE ON YOUR LOGIC
        }
    }
}

Step 3:-

Run below commands and check the result.

  1. php bin/magento c:f
  2. php bin/magento s:s:d

NOTE:- Above plugin logic is sample logic, you can modify as per your requirement.

I hope this will help you to achieve your requirement.

Thanks

0

Obviously seems pretty simple.

On your product controller page, check his stock and depending on the result, either you continue as normal on the product page either you make the redirection.

To handle the redirectionuse Magento\Framework\App\ResponseFactory;

            $resultRedirect = $this->responseFactory->create();
            $resultRedirect->setRedirect($redirectUrl)->sendResponse('200');

You just have to retrieve the category product url. $product->getCategory()->getUrl()

1
  • Hello, can you kindly add full code as answer ?
    – user104369
    Commented Dec 1, 2022 at 9:09
0

It is possible to redirect a product to its assigned category page if it is out of stock in Magento 2. You can achieve this by creating a custom module and using the event observer to listen to the catalog_product_save_after event. In the observer, you can check if the product is out of stock and redirect it to the assigned category page.

Steps to Achieve This:

Create a custom module by creating a module.xml file in app/code/[Vendor]/[Module]/etc directory and add the following code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xml">
    <module name="[Vendor]_[Module]" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Create an events.xml file in app/code/[Vendor]/[Module]/etc/frontend directory and add the following code to register the event observer:

<?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="catalog_product_save_after">
        <observer name="[module]_redirect_outofstock_product" instance="[Vendor]\[Module]\Observer\RedirectOutOfStockProductObserver" />
    </event>
</config>

Create a RedirectOutOfStockProductObserver.php file in app/code/[Vendor]/[Module]/Observer directory and add the following code to implement the event observer:

<?php
namespace [Vendor]\[Module]\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class RedirectOutOfStockProductObserver implements ObserverInterface
{
    protected $_productRepository;

    public function __construct(
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->_productRepository = $productRepository;
    }

    public function execute(Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();

        if ($product->getIsInStock() === false) {
            $categoryIds = $product->getCategoryIds();
            $categoryId = $categoryIds[0];

            $redirectUrl = $this->_productRepository->getById($product->getId())->getUrlInStore(['_query' => ['SID' => '', '___store' => $product->getStoreId()]]);
2
  • This will redirect on product save. The original author was I think searching to redirect when he goes on the product page itself. So here the on save observer is not needed from my perspective. He just have to place this to a preference of the product controller page. May be i'm wrong. Your code is right though.
    – Claims
    Commented Dec 5, 2022 at 15:08
  • Currently, I am not getting the out-of-stock products from the configurable product on the product page (product/view controller).
    – user104369
    Commented Dec 8, 2022 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.