So I am creating a Magento product when I call this if statement and it returns false, that all works...

I just want to create the URL or create a URL redirect for the product in the same statement

It needs to be within the same if statement as I want it to be created at the same time of the product creation

Here is my code:

if (!Mage::getModel('catalog/product')->getIdBySku($sku))  {

  $product = Mage::getModel('catalog/product');

    'use_config_manage_stock' => 0,
    'qty' => 0,
    'min_qty' => 0,
    'min_sale_qty' => 1,
    'max_sale_qty' => 9999,
    'is_qty_decimal' => 0,
    'backorders' => 0,
    'notify_stock_qty' => 0,
    'is_in_stock' => 0

  $product->setTaxClassId(2);     // default tax class
  $product->setAttributeSetId(4); //9 is for default

  $product->setStatus(1);//1=Enabled; 2=Disabled;
  $product->setVisibility(4);//4 = catalog & search.

  } catch(Exception $e) {
    echo $e->getMessage();

You can try using setUrlKey() like this:

$url = preg_replace('#[^0-9a-z]+#i', '-', $name);
$url = strtolower($url);

Otherwise I think you may need to rewrite the product url.

Take a look at:

app/code/core/Mage/Catalog/Model/Url.php, Mage_Catalog_Model_Product_Url and Mage_Core_Model_Url_Rewrite


You are missing a $product->setUrlKey(..); which sets the url key you want. Probably you need to rebuild the catalog_url index after saving.

  • This doesn't work. I should have stated this in my original question. I always end up getting the name converted into a url-encoded string automatically set as the URL. $product->setUrlKey($sku); does not have any effect. – Gary Frey May 19 '15 at 19:39
  • Did you flush the cache and reindex the catalog_url? This solved the problem for me. – luemic May 19 '15 at 20:13
  • Yes of course, the URL key is always automatically set to a string version of the name of the product. – Gary Frey May 19 '15 at 20:17
  • To clarify, if i do not set a name fort the product then no URL is generated, even if I try to set $product -> setUrlKey($url); – Gary Frey May 19 '15 at 20:18
  • Maybe for some reason your url key is a store view/website specific setting? – luemic May 19 '15 at 20:19

Instead of using preg_replace

it's better to use in formatUrlKey() of Magento\Catalog\Model\Product

you can send it any string yow want

(recommended to add the sku to the product name)

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.