Skip to content

Instantly share code, notes, and snippets.

@sylvainraye
Created June 24, 2014 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylvainraye/cfcb934b4e6013cc5de6 to your computer and use it in GitHub Desktop.
Save sylvainraye/cfcb934b4e6013cc5de6 to your computer and use it in GitHub Desktop.
Display the product of a category only if this one has a unique product in Magento
/**
* Display the product of a category only if this one has a unique product
*
* Event
* - catalog_controller_category_init_after
*
* @param Varien_Event_Observer $observer
* @return mixed
*/
public function initSingleProductRedirect(Varien_Event_Observer $observer)
{
/* @var $category Mage_Catalog_Model_Category */
$category = $observer->getEvent()->getCategory();
$action = $observer->getEvent()->getControllerAction();
if ($category->getProductCount() == 1 && $category->getChildrenCount() <= 0) {
$resource = $category->getResource();
$sql = $resource->getReadConnection()->select()
->from(array('cat' => $resource->getTable('catalog/category_product')), 'product_id')
->where('cat.category_id = ?', $category->getId());
$productId = $resource->getReadConnection()->fetchOne($sql);
$url = Mage::getModel('catalog/product')->load($productId)->getProductUrl();
if ($url) {
return $action->getResponse()->setRedirect($url);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment