In this post I will show you how to get the parent URL of a child product EFFICIENTLY (that means, unlike the very common mistake most Magento developers do, it is a way that will not slow your website down).
Let's say you have configurable products in your Magento site.
Each configurable product has 1 parent product (configurable product) and some (let's say 2) children (simple product). Let's say you wish to display the product list on your category page, but each product should have it's parent URL.
Lets implement this:
I assume you wish to implement this in base/default/template/catalog/product/list.phtml
<?php $i=0; foreach ($_productCollection as $_product): $prodId = $_product->getId(); $arrayOfParentIds = Mage::getSingleton("catalog/product_type_configurable") ->getParentIdsByChild($prodId); $parentId = (count($arrayOfParentIds) > 0 ? $arrayOfParentIds[0] : null); $url = $_product->getProductUrl(); if(!is_null($parentId)){ $url = Mage::getModel("catalog/product")->load($parentId)->getProductUrl(); } ?>
This implementation will work, but it isn't recommended when performing on a large collection (more than 5 products / page). why? Because, the action
Mage::getModel("catalog/product")->load($parentId);
is pretty expensive in terms of efficiency (in other words - it takes large amount of time for the server to perform this action). looping on this action more than once or twice will slow your website down dramatically.
So here is the alternative. might be more complicated, but a lot more efficient (implementation):
<?php $rewrite = Mage::getModel('core/url_rewrite'); $params = array(); $params['_current'] = false; ?> <?php $i=0; foreach ($_productCollection as $_product): $prodId = $_product->getId(); $arrayOfParentIds = Mage::getSingleton("catalog/product_type_configurable") ->getParentIdsByChild($prodId); $parentId = (count($arrayOfParentIds) > 0 ? $arrayOfParentIds[0] : null); $url = $_product->getProductUrl(); $idPath = 'product/'.$parentId; $rewrite->loadByIdPath($idPath); $parentUrl = Mage::getUrl($rewrite->getRequestPath(), $params); $url = ($parentUrl ? $parentUrl : $url); ?>
This implemenation is much more cheaper in terms of efficiency, because we use
$rewrite->loadByIdPath($idPath);
instead of the expensive
Mage::getModel("catalog/product")->load($parentId);
which means, less loading time.
That's all :-)