Magento – Get page URL from current page, different store-view

hreflangmagento-1multistorestore-viewurl

I'm using different store-views to create different language versions of a shop. Now I'm trying to add links to the other pages. However, I can not find a way to get the actual URL from the other store, if the url of that page / product / category is changed for that store (in this case, translated). I've got the following code at this moment:

<?php
// Get the current website
$website = Mage::app()->getWebsite();
// Only get languages/stores from the current website
$stores = $website->getStores();
// loop through the stores
foreach ($stores as $_lang):
    // If it's not the current store, create an alternative for it
    if( $_lang->getId() != Mage::app()->getStore()->getStoreId() ){ 
        // Get the language code for that store view
        $lang_code = substr(Mage::getStoreConfig('general/locale/code', $_lang->getId()),0,2);
        // Create a link, using getCurrentUrl for the set store ?>
        <link rel="alternate" hreflang="<?php echo $lang_code; ?>" href="<?php echo $_lang->getCurrentUrl(); ?>" />
    <?php } ?>
<?php endforeach; ?>

However, this returns the same URL, with a ?___store=fr&___from_store=nl at the end. It should however give the URL from the different store, which has a different url key.
I've also tried the following:

Mage::getUrl('', array(
    '_current' => true,
    '_use_rewrite' => true,
    '_secure' => true,
    '_store' => $_lang->getId(),
    '_store_to_url' => true
));

But this gave the exact same results.

Is there a way to retrieve the right URL without having to use a redirect?

Best Answer

When accessing the alternate link which your code generates Magento should rewrite and redirect to the correct URL. You can take a look at Mage_Core_Model_Url_Rewrite_Request::_rewriteDb to see this rewrite process.

Basically it maps the request path from the ___from_store scope to the ___store scope.

You could mimic this rewrite process but I would advise against it. You would be performing a lot of database actions without knowing if the result will be used or not, and seeing that the 'ugly' URL is eventually redirect to the correct 'pretty' URL anyway, it doesn't seem to matter, especially if you're outputting these URL's in a non-visible way.

Regards, Vincent