April 3, 2020 08:14 by
Peter
In this post, I will show you how to get a products URL on Magento. There is 3 methods you can use, all of which are in Mage_Catalog_Model_Product. And here is the code:
public function getUrlPath($category=null)
public function getUrlInStore($params = array())
public function getProductUrl($useSid = null)
The simplest way to explain is to just show the results of many calls. Given a product whose URL key is scott-large-coffee-table-set-multicolour upon the domain of http :// created. local the results are :
$product->getUrlPath();
'scott-large-coffee-table-set-multicolour'
$product->getUrlPath($category);
'tables/scott-large-coffee-table-set-multicolour'
// you cannot stop this method adding ___store to the URL, even by setting _store_to_url to false
$product->getUrlInStore();
'http://made.local/tables/scott-large-coffee-table-set-multicolour?___store=default'
// you cannot stop this method adding ___store to the URL, even by setting _store_to_url to false
// note - see the "using _ignore_category" section below for an arguable bug with using this param
$product->getUrlInStore(array('_ignore_category' => true));
'http://made.local/scott-large-coffee-table-set-multicolour?___store=default'
$product->getProductUrl();
'http://made.local/tables/scott-large-coffee-table-set-multicolour'
$product->getProductUrl(true);
'http://made.local/tables/scott-large-coffee-table-set-multicolour'
To discover what some other params could be passed to getUrlInStore (), notice URL Route Parameters. Using _ignore_category. The brief version, I wouldn't use this param, and rather use Mage: getUrl ($product-getUrlPath ())
In case you first fetch a products URL that contains the category, then use a similar product instance to commit to fetch a non-category URL, you'll rather both times obtain a URL that includes the category, begin to see the below code :
$product = Mage::getModel('catalog/product');
$product->getUrlInStore();
'http://made.local/sofas/peter-2-seater-sofa-blue?___store=default'
$product->getUrlInStore(array('_ignore_category' => true));
'http://made.local/sofas/peter-2-seater-sofa-blue?___store=default'
$product = Mage::getModel('catalog/product');
$product->getUrlInStore(array('_ignore_category' => true));
'http://made.local/peter-2-seater-sofa-blue?___store=default'
The problem lies using the request_path key upon the $product model, that the Mage_Catalog_Model_Product_Url : : getUrl () sets, to become a cached worth for an otherwise intensive method of resolving a URL rewrite to an item inside a category.
To solve this, unset request_path first, as beneath :
$product->unsRequestPath();
$product->getUrlInStore(array('_ignore_category' => true));
'http://made.local/peter-2-seater-sofa-blue?___store=default'
Note which any technique outlined in the top of the card that leads to the category to be present inside the returned URL can have a similar effect of caching the category.