0

I am creating Product Programtically. right now, i am giving product name as url for newly created Product, but i want to give product sku as url key .

example : Original Product : name : test [url key = test1 , sku = 1234 ]

Programtcally created Product : name : test [url key = test1 , sku = abcd ]

Instead of test1 i want to give new product's url-key as abcd, so that i can see in site with this url : sitename.com/abcd.html

public function saveProduct($type, $doSave = true, $originalProduct, $newImagePath) 
{
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
            $product = Mage::getModel('catalog/product');

            $rand = rand(11, 999999999);
            $product->setTypeId($type)
            ->setSku('CDSB1_sku' . $rand);

            $product->setIsMassupdate(true)->setExcludeUrlRewrite(true);
            $product->setName($originalProduct->getName());
            $product->save();   
}

if that is not possible atleast i want to give some random number for "Url Key"

1

You can set url key of product like this-

public function saveProduct($type, $doSave = true, $originalProduct, $newImagePath) 
{
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
            $product = Mage::getModel('catalog/product');

            $rand = rand(11, 999999999);
            $product->setTypeId($type)
            ->setSku('CDSB1_sku' . $rand);
            $product->setUrlKey($rand); // change $rand with sku to set sku as url
            $product->setIsMassupdate(true)->setExcludeUrlRewrite(true);
            $product->setName($originalProduct->getName());
            $product->save();   
}

To redirect to the programmatically created product use this in your controller-

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$this->_redirect($product->getUrl());
  • your solution worked fine, when i try to see product in site as sitename.com/5678.html , its giving 404 error, but when i edit the url key manually and save product and when i check in site, it works fine, is there any way to solve this ? – user52996 May 18 '17 at 10:19
  • try after reindexing – Piyush May 18 '17 at 10:19
  • i will check it and inform you..... – user52996 May 18 '17 at 10:20
  • sorry, one more thing, after new product is creating with new url , is there any way to redirect to that new product url ? – user52996 May 18 '17 at 10:29
  • I have updated my answer – Piyush May 18 '17 at 10:39

Your Answer

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