0

After looking at various methods, the following code is almost getting what I want:

 $product = Mage::getModel('catalog/product')->load($product_id);
 $site_url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
 $product_url = '';
 $cats = $product->getCategoryIds();
 if (sizeof($cats)) {
     $category = Mage::getModel('catalog/category')->load((int) $cats[0]);
     $product_url = $site_url.$product->getUrlPath($category);
 }

This returns: http://magento.dev/men/shirts/french-cuff-cotton-twill-oxford-570.html.

However this produces a 404.

570 is not the ID that corresponds to this product so I'm wondering where it's coming from.

0

Instead of using $product_url = $site_url.$product->getUrlPath($category); those.

You use below code

 $product = Mage::getModel('catalog/product')->load($product_id);
 $product_url = '';
 $cats = $product->getCategoryIds();
 if (sizeof($cats)) {
     $category = Mage::getModel('catalog/category')->load((int) $cats[0]);
   if($category->getId()){
    $product->setCategory($category);
   }
 }
$product_url = $product->getProductUrl();

Or via ProductCollection with addUrlRewrite() function:

$product = Mage::getModel('catalog/product')->load($product_id);
 $product_url = $product->getProductUrl();
 $cats = $product->getCategoryIds();

 if (sizeof($cats)) {
   $collection = Mage::getResourceModel('catalog/product_collection');
   $collection->addIdFilter($product->getId());
   if($collection->getSize() >= 1):
      /* Add addUrlRewrite for add category url with product */
       $collection->addUrlRewrite((int)$cats[0]);
       $ProductWithCategory = $collection->getFirstItem();
       $product_url = $ProductWithCategory->getProductUrl();
   endif;  
 }
  • Thanks Amit. The first recommendation worked and produced the url: magento.dev/index.php/catalog/product/view/id/402/s/… The second solution didn't seem to do what was expected. It produced the URL: magento.dev/index.php/catalog/product/view/id/402 This seems less "url-rewritten" than the first one. It seems insane but I'm now seriously considering sticking with my original method but doing a REGEX replace on the ID to produce the correct URL. Only by doing this horrible hack will I get the URL that the front-end uses. – mikejw Mar 27 '17 at 9:53
  • Please do indexing from shell check and check the result – Amit Bera Mar 27 '17 at 9:57
  • Hi Amit, I've successfully run "php indexer.php --reindex" and "php indexer.php --reindex all". This has no impact on the results I'm getting. – mikejw Mar 27 '17 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.