December 14, 2018

cm-mini

Thinking Magento

Update Product URL's Programmatically with 301 redirect

Recently I needed to update the URL's of existing products, without losing the 301 redirects. There are ways of course of doing this with extensions and uploading CSV's to extensions, however I decided to take a different route and update the URL's programmatically. 

Created a PHP file and placed it in root, in this case we can call it URL_UPDATER.php and added the following code. Set the ID's that you would like update to avoid overloading your database. Job don.

<?php 

require_once 'app/Mage.php';
Mage::app();
umask(0);
/*Set store to be admin so that you the URL change affects global*/
Mage::app()->setCurrentStore('0');

/*Build collection of products*/
$collection = Mage::getResourceModel('catalog/product_collection');

/*Set the product ID range of products you would like to adjust 7157 - 7357*/
$collection->addFieldToFilter('entity_id', array('gt' => 7156));
$collection->addFieldToFilter('entity_id', array('lt' => 7358));
$collection->getAllIds();

foreach($collection as $id) {

/*Get the ID of the product to load*/
$load = $id['entity_id'];

/*Load the product*/
$_product = Mage::getModel('catalog/product')->load($load);

/*New URL based on product name*/
$new_url = Mage::getModel('catalog/product_url')->formatUrlKey($_product->getName());

// save rewrites history for old to new url redirect
$_product->setData('save_rewrites_history', true);

// set new url
$_product->setUrlKey($new_url);

// set new url path
$_product->setUrlPath($new_url);

// save the product
$_product->save();

}