How To Redirect Magento 2 Simple Product To Its Configurable Parent

by admin

Can we redirect Magento 2 simple product to its configurable parent? The answer is yes, and here’s how you do it.

Sometimes, Magento 2 store owners set up a website where simple products are shown in the category listings, and the configurable products for these items are in a hidden category.

And they want to add some functionality, so when a customer clicks on one simple product, it redirects them to the configurable product with attributes pre-selected.

For example, you have 2 simple products:

  • Red XM headphone
  • Blue XM headphone

And a configurable product: 

  • XM headphone

The Red and Blue headphones are visible in the search. But when the user clicks on one of those simple products, the configurable product page would be opened instead, but the right color should be pre-selected.

So how can you do it? Magento 2 assign simple product to configurable programmatically is the best solution!

Full Guide To To Redirect Magento 2 Simple Product To Its Configurable Parent

To enable Magento 2 assign simple product to configurable programmatically, please do the following steps:

Building a basic Magento 2 module

First, we need to create some necessary files and folders so Magento 2 can recognize the module.

Create /app/code/DaanvdB/RedirectSimpleProducts/registration.php file then add the following code to it:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'DaanvdB_RedirectSimpleProducts',
    __DIR__
);

Create /app/code/DaanvdB/RedirectSimpleProducts/etc/module.xml file then add the following code to it:

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

Run php bin/magento setup:upgrade so Magento can update and add the new module to its configuration.

Redirect Magento 2 simple product to configurable using an Observer

Next, we need to create an observer that hooks into an event that is triggered before the catalog_product_view is requested. 

The best event is controller_action_predispatch_catalog_product_view.

Create the custom Observer-class in /app/code/DaanvdB/RedirectSimpleProducts/Observer/Predispatch.php then add the following code:

<?php

namespace DaanvdB\RedirectSimpleProducts\Observer;

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

class Predispatch implements ObserverInterface {

    protected $_redirect;
    protected $_productTypeConfigurable;
    protected $_productRepository;
    protected $_storeManager;

    public function __construct (
        \Magento\Framework\App\Response\Http $redirect,
        \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $productTypeConfigurable,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->_redirect = $redirect;
        $this->_productTypeConfigurable = $productTypeConfigurable;
        $this->_productRepository = $productRepository;
        $this->_storeManager = $storeManager;
    }

    public function execute(Observer $observer)
    {
        $pathInfo = $observer->getEvent()->getRequest()->getPathInfo();

        /** If it's not a product view we don't need to do anything. */
        if (strpos($pathInfo, 'product') === false) {
            return;
        }

        $request = $observer->getEvent()->getRequest();
        $simpleProductId = $request->getParam('id');
        if (!$simpleProductId) {
            return;
        }

        $simpleProduct = $this->_productRepository->getById($simpleProductId, false, $this->_storeManager->getStore()->getId());
        if (!$simpleProduct || $simpleProduct->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) {
            return;
        }

        $configProductId = $this->_productTypeConfigurable->getParentIdsByChild($simpleProductId);
        if (isset($configProductId[0])) {
            $configProduct = $this->_productRepository->getById($configProductId[0], false, $this->_storeManager->getStore()->getId());
            $configType = $configProduct->getTypeInstance();
            $attributes = $configType->getConfigurableAttributesAsArray($configProduct);

            $options = [];
            foreach ($attributes as $attribute) {
                $id = $attribute['attribute_id'];
                $value = $simpleProduct->getData($attribute['attribute_code']);
                $options[$id] = $value;
            }

            $options = http_build_query($options);
            $hash = $options ? '#' . $options : '';
            $configProductUrl = $configProduct->getUrlModel()
                ->getUrl($configProduct) . $hash;
            $this->_redirect->setRedirect($configProductUrl, 301);
        }
    }
}

The Observer we just created is to take care of the following process:

  1. It checks if we are on a catalog_product_view-page
  2. It checks if the current request is a simple product
  3. In case it is, it finds its corresponding configurable parent and loads all available configurable attributes
  4. It takes the values for each configurable attribute and builds an options array
  5. With the array, it builds a query using Magento’s integrated URL parsing functionality
  6. The created query is attached to the configurable products’ URL-key, and a Redirect is set.

Adding the Observer-class to an event

To trigger the custom Observer, we need to create a file called events.xml.

Create /app/code/DaanvdB/RedirectSimpleProducts/etc/events.xml file:

<?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="controller_action_predispatch_catalog_product_view">
        <observer name="daanvdb_redirectsimple_products_observer_predispatch" instance="DaanvdB\RedirectSimpleProducts\Observer\Predispatch"/>
    </event>
</config>

The events.xml takes care of triggering the custom observer whenever the controller_action_predispatch_catalog_product_view is called.

Finally, clear the cache. And you’re done!

The Solution To Optimize Your Configurable Product Pages

Hereby, we want to introduce you to a very beneficial extension to help you simplify and optimize your configurable products’ appearance:

Magento 2 Simple Details on Configurable Product by BSS

magento-simple-details-on-configurable-product

This Magento change simple product to configurable module allows you to show child item details of the configurable product, including URL and metadata, name and SKU, price and special price, images, short description and full description, “More information” tab, stock status and quantity.

Thanks to this Magento 2 add simple product to configurable programmatically, your customers can see all details of one selected option without page reload.

The extension also showcases child products on the Dynamic Category/Product Listing Page with a review swatch.

Magento 2 Simple Details on Configurable Product by BSS enable you to select a suitable way to display product images in 3 ways, depending on what configurable products you sell:

  • Display all parent product images instead of child product images.
  • Display child product images at the beginning of parent product images.
  • Display only the parent product’s images even when the user selects the child product option.

And it generates child product metadata automatically to help you optimize your SEO.

Using this extension, each time a customer choose an option in the frontend, the URL will be updated accordingly.

Check out the list of highlight features:

  • Dynamic content updates: name, SKU, descriptions, and other attributes;
  • Generate a URL for each selected option;
  • Preselect options for multiple purposes;
  • Enrich customer shopping experiences and buying conveniences;

Conclusion

In this article, we have shown you a comprehensive tutorial on how to redirect a Magento 2 simple product to its configurable parent with attributes pre-selected.

We hope this Magento 2 add simple product to configurable programmatically guide is helpful and good luck to you!

BSS Commerce is one of the leading Magento extension providers and web development services in the world. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize your business effectively. Furthermore, we offer FREE Installation – FREE 1-year Support and FREE Lifetime Update for every Magento extension.

CONTACT NOW to let us know your problems. We are willing to support you every time.

 

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.