Magento – Get Group Product Path(URL) from Single Product ID

grouped-productsproducturl

Given that I already have the single product id, was it possible to get it's grouped product url that has the certain single product id that I got?

For example,

I got a single product id of 11

Group_Product_1

  1. Single1 (product id = 10)
  2. Single2 (product id = 11)
  3. Single3 (product id = 12)

Group_Product_2

  1. Single4 (product id = 13)
  2. Single5 (product id = 14)
  3. Single6 (product id = 15)

What I want to happen is get the GROUP PRODUCT URL that has a single product id of 11

Well I have this certain sample code,

$singleId = 11;

//Check if product type is grouped
if ($_product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED) {

    //Get group product's id from single product's id
    $parentId = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($singleId);

    $groupProduct = Mage::getModel('catalog/product')->load($parentId); 
    $groupPath = $groupProduct->getProductUrl();

    echo $groupPath;
}

But what I'm getting is…

mysite.com/catalog/product/view/category/312

It does redirect me to somewhere that page does not exist (page 404)

Any solution for this stuff?

Best Answer

I think that the problem you are having is that the simple product will have the type simple and not grouped. If you update your code to not check type but if the returned parentids array is empty then your code should work as desired.

$product = Mage::getModel('catalog/product')->load($singleId);
$parentIds = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($product->getId());
foreach($parentIds as $parentId) {
    $groupProduct = Mage::getModel('catalog/product')->load($parentId);
    $groupPath = $groupProduct->getProductUrl();

    echo $groupPath;
}
Related Topic