Saturday, February 20, 2016

Get Full Product URL Including Category in Magento


Magento is e-commerce open source for based on PHP for creating shopping based website all over the world. If you are Magento developer or need some customization in Magento that must need Magento product page URL for display product anywhere in the website.
For getting product URL in Magento use `getProductUrl()`  function. when you visit product from category listing that it's display full URL with category and when use getProductUrl() function that it's display only product URL and also change breadcrumbs.so that time you must need full product URL.so just create new function in product model.
open file `app/code/local/Mage/Catalog/Model/Product.php` and add below function in `Mage_Catalog_Model_Product` class.


public function getFullProductUrl( $product ){
 if(is_object($product) && $product->getSku()){
 $proArr = $product->getCategoryIds();
 // first try SQL approach
 try{
  $query      = "SELECT `request_path` FROM `".Mage::getConfig()->getTablePrefix()."core_url_rewrite` WHERE `product_id`='" . $product->getEntityId() . "'".((end($proArr)) ? 'AND `category_id`='.end($proArr) : '')." AND `store_id`='" . Mage::app()->getStore()->getId() . "';";
  $read       = Mage::getSingleton('core/resource')->getConnection('core_read');
  $result     = $read->fetchRow($query);
  return Mage::getUrl('').$result['request_path'];
 }
 catch(Exception $e){
  $allCategoryIds     = $product->getCategoryIds();
  $lastCategoryId     = end($allCategoryIds);
  $lastCategory       = Mage::getModel('catalog/category')->load($lastCategoryId);
  $lastCategoryUrl    = $lastCategory->getUrl();
  $fullProductUrl     = str_replace(Mage::getStoreConfig('catalog/seo/category_url_suffix'), '/', $lastCategoryUrl) . basename( $product->getUrlKey() ) . Mage::getStoreConfig('catalog/seo/product_url_suffix');
  return $fullProductUrl;
 }
  }
  return false;
}

Now call below function in theme files by call product model use below code for get full product URL.

 
$getproduct =Mage::getModel('catalog/product')->load($productid); //use $_products->getId();
$getproduct ->getFullProductUrl($getproduct ); 


Here you can also create own extension by extend `Mage_Catalog_Model_Product` class and add below function in that class if you want to not change magento core files.

No comments :

Post a Comment