Magento 1.9 Product URLs – How to Get Product URLs of Each Store View

magento-1.9PHPproduct-urls

I have 2 store view:

  • www.example.com (EN Store)
  • www.example.it (IT Store)

and I have 2 different urls that point at the same products:

  • www.example.com/car-honda-civic.html (<— I want obtain this url)
  • www.example.it/auto-honda-civic.html (<— and I want obtain this url)

and I use some php function to redirect the users to the right store based on user's language browser (parsing $_SERVER['HTTP_ACCEPT_LANGUAGE']).

I'm trying to get these links into a separate Magento folder and page:

www.example.com/myproject/mypage.php

and this is what I tried to do:

// REQUIRE MAGENTO ESSENTIAL CODE
require_once("../app/Mage.php");
umask(0);

// I NEED TO GET ONLY GROUPED PRODUCTS
$collection = Mage::getResourceModel('catalog/product_collection');
$grouped_collection = array();

foreach($collection as $product) {
    if ($product->getTypeId() == 'grouped') {
      //echo $product->getId();  
      array_push($grouped_collection, $product->getId());
    }
}

// E.G.: LOAD PRODUCT 12
$productId = $grouped_collection[12];
$product = Mage::getModel('catalog/product')->load($productId);

// I TRYING TO GET PRODUCT URLS OF EACH STORE VIEW
$productLinkEn = $product->getUrlInStore(array("_store" => "en")); 
$productLinkIt = $product->getUrlInStore(array("_store" => "it")); 

echo $productLinkEn; //Output: http://www.example.com/auto-honda-civic.html?SID=2fdsfsd34fsdfsdf34$__store=en
echo $productLinkIt; //Output: http://www.example.it/auto-honda-civic.html?SID=2fdsfsd34fsdfsdf34$__store=it

How can I get both clean above urls product?

Best Answer

Better approach imo would be to look up product url using core_url_rewrite table. At least you avoid full product load.

    $productUrls = array();
    $idPath = 'product/887';

    $rewrite = Mage::getResourceModel('core/url_rewrite');
    $read = $rewrite->getReadConnection();

    $select = $read->select()
        ->from($rewrite->getMainTable(), array('store_id', 'request_path'))
        ->where('id_path = ?', $idPath);
    $data = $read->fetchPairs($select);

    foreach (Mage::app()->getStores() as $store) {
        if (isset($data[$store->getId()])) {
            $baseUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK, null);
            $productUrls[$store->getId()] = $baseUrl . $data[$store->getId()];
        }
    }

    Zend_Debug::dump($productUrls);