Magento – How to get Product Target Path programmatically in product edit page

magento-1.9PHP

I'm trying to get the latest Target Path to show up in the backend of Magento on the product edit page.

I've tried everything I can think of to try to get it but I usually get NULL.

I've managed to do this to get the URL key…

$productId = $this->getProductId();
$path = Mage::getResourceSingleton('catalog/product')->getAttributeRawValue($productId, 'url_key', Mage::app()->getStore());
echo $path;

Which gives 'sample-url-key', however, I'm trying to get the latest Target Path – the actual path on the frontend since 2 products have this URL and this product's target path is actually 'sample-url-key-14'.

I can't seem to get it to load by using

 $rewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath($path)

or

$rewrite = Mage::getModel('core/url_rewrite')->loadByIdPath($path)

These both return NULL.

I've also tried another method I read about

$product_collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id', $productId)
->addUrlRewrite();
$path = $product_collection->getFirstItem()->getProductUrl();
echo $path;

This $path returns https://example.com/index.php/catalog/product/view/id/14/

I'm trying to find a way to show what the actual URL will be when viewing this product on the frontend, not what is just in the URL key field since that's not accurate for duplicate/rewritten URLs.

Best Answer

Try this:

<?php echo Mage::getModel('catalog/url')->generatePath('target', $_product);?>
Related Topic