Get the Parent URL of a Child Product
Posted on August 16, 2011 by admin There have been 2 comment(s)
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 :-)
This post was posted in Configurable products and was tagged with configurable products, speeding up magento site, efficient code with magento
Thanks!! spared me alot of efforts debugging and understanding one old script that keeps on crashing down
Posted on June 11, 2012 at 12:55
can you explain haow it works: $rewrite->loadByIdPath($idPath); ?
Posted on August 1, 2012 at 13:00