Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redirect Simple Products to Configurable Parents with Options Preselected in Magento 1
<?xml version="1.0"?>
<config>
<modules>
<DaanvandenBergh_RedirectSimpleProducts>
<version>1.0.0</version>
</DaanvandenBergh_RedirectSimpleProducts>
</modules>
<global>
<models>
<daanvandenbergh_redirectsimpleproducts>
<class>DaanvandenBergh_RedirectSimpleProducts_Model</class>
</daanvandenbergh_redirectsimpleproducts>
</models>
</global>
<frontend>
<events>
<controller_action_predispatch_catalog_product_view>
<observers>
<daanvandenbergh_redirectsimpleproducts>
<class>daanvandenbergh_redirectsimpleproducts/observer</class>
<method>redirectToConfigurable</method>
</daanvandenbergh_redirectsimpleproducts>
</observers>
</controller_action_predispatch_catalog_product_view>
</events>
</frontend>
</config>
<?xml version="1.0"?>
<config>
<modules>
<DaanvandenBergh_RedirectSimpleProducts>
<codePool>local</codePool>
<active>true</active>
<depends>
<Mage_Catalog />
</depends>
</DaanvandenBergh_RedirectSimpleProducts>
</modules>
</config>
<?php
class DaanvandenBergh_RedirectSimpleProducts_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] );
$productAttributeOptions = $mainProduct->getTypeInstance( true )->getConfigurableAttributesAsArray( $mainProduct );
$attributeOptions = array();
foreach ( $productAttributeOptions as $productAttribute ) {
$simpleProduct = Mage::getModel( 'catalog/product' )->getCollection()
->addAttributeToFilter( 'entity_id', array( 'eq' => $id ) )
->addAttributeToSelect( $productAttribute['attribute_code'] )
->setPageSize( 1 )
->getFirstItem();
$attributeOptions[ $productAttribute['attribute_id'] ] = $simpleProduct->getData( $productAttribute['attribute_code'] );
}
Mage::getSingleton( 'core/session' )->setSuperAttributes( $attributeOptions );
Mage::app()->getResponse()->setRedirect( $mainProduct->getProductUrl(), 301 );
Mage::app()->getResponse()->sendResponse();
exit;
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment