How to Get Correct Product URL Based on Store View in Magento 1.9

magento-1.9PHPproduct-urlsstore-viewurl-rewrite

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.

So, if I try to get product url (from my browser with italian language set) with:

$product->getUrlInStore(array("_store" => "en")); –> http://www.example.com/auto-honda-civic.html?SID=2fdsfsd34fsdfsdf34$__store=en

$product->getUrlInStore(array("_store" => "it")); –> http://www.example.it/auto-honda-civic.html?SID=2fdsfsd34fsdfsdf34$__store=it

How can I get both clean above urls product?


— EDIT —

For completeness I add this:

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

www.example.com/myproject/mypage.php

and to load products I use:

require_once("../app/Mage.php");
umask(0);

$collection = Mage::getResourceModel('catalog/product_collection');
$grouped_collection = array();

// I need to get only grouped products
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);

$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

Best Answer

if you are loading product then you just need to set store id in product object like below

   $store = Mage::app()->getDefaultStoreView();
   // Gets the current store's id
   $this->_storeId = $store->getStoreId();
   $product->setStoreId($this->_storeId);

and then you can try with echo $product->getProductUrl();

Related Topic