Magento – Delete url rewrite programmatically

programmaticallyurl-rewrite

I need to set some url rewrites for different pages. But when I started my CLI script, I had some issue "Request Path for Specified Store already exists."
That's why I need to delete this url rewrite before. How can I do it programmatically.

Option to find this URL must be "Request Path", because ID of this url can be different on the test server and live site.

Please provide me, how can I do it.

Best Answer

Take a look at Mage_Core_Model_Url_Rewrite class. This class provides a loadByRequestPath($path) method which seems to be what you need

So, code would be...

//$path is your request_path
$rewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath($path);
if ($rewrite->getId()){
    // rewrite exists
    $rewrite->delete();
}

Other way could be working with collections

$c = Mage::getModel('core/url_rewrite')->getCollection();
$c->addFieldToFilter('request_path', array('eq' => $path));
foreach ($c->getItems() as $rewrite){
    $rewrite->delete();
}

I don't know the amount of URLs you need to delete, nor the format you have the data. So, choose the more appropriate way to you

Related Topic