How to redirect a simple product's page to the parent configurable product page?
1 Answer
the code below should work only if the simple products are assigned to only one configurable product.
by default, magento allows you to add a simple product to as many configurable products you need.
Let's create a module and call it StackExchange_Redirect
.
You will need the following files.
app/etc/modules/StackExchange_Redirect.xml
- the declaration file
<?xml version="1.0"?>
<config>
<modules>
<StackExchange_Redirect>
<codePool>local</codePool>
<active>true</active>
<depends>
<Mage_Catalog />
</depends>
</StackExchange_Redirect>
</modules>
</config>
app/code/local/StackExchange/Redirect/etc/config.xml
- the module configuration file where you declare an observer for the product view page
<?xml version="1.0"?>
<config>
<modules>
<StackExchange_Redirect>
<version>1.0.0</version>
</StackExchange_Redirect>
</modules>
<global>
<models>
<stackexchange_redirect>
<class>StackExchange_Redirect_Model</class>
</stackexchange_redirect>
</models>
</global>
<frontend>
<events>
<controller_action_predispatch_catalog_product_view>
<observers>
<stackexchange_redirect>
<class>stackexchange_redirect/observer</class>
<method>redirectToConfigurable</method>
</stackexchange_redirect>
</observers>
</controller_action_predispatch_catalog_product_view>
</events>
</frontend>
</config>
app/code/local/StackExchange/Redirect/Model/Observer.php
- the observer that should redirect to the configurable product page.
<?php
class StackExchange_Redirect_Model_Observer
{
public function redirectToConfigurable($observer)
{
$id = Mage::app()->getRequest()->getParam('id');
$configurableParentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
->getParentIdsByChild($id);
if (isset($configurableParentIds[0])) {
$mainProduct = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($configurableParentIds[0]);
Mage::app()->getResponse()->setRedirect($mainProduct->getProductUrl(), 301);
Mage::app()->getResponse()->sendResponse();
exit;
}
return $this;
}
}
when you are done, clear the cache.
-
-
-
It returns the error Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting '{' /Model/Observer.php on line 4– yavonz15Mar 3, 2016 at 12:12
-
1
-