skip to Main Content

I need to add redirect for 30 urls in 3 stores. For that I have created a script, using that I can add the urls, but the issue with the script is if the request path already exists I have to delete the entry and insert the new one. I have used the below code for that, it doesn’t deletes the already existing entry(is_system=>1 for this entry). Can anyone help me solve this.

$rewrite_collection = Mage::getModel('core/url_rewrite')->getCollection();
$rewrite_collection->addFieldToFilter('request_path', array('eq' => 
$request_path));
$rewrite_collection->addFieldToFilter('store_id', array('eq' => 1));
$rewrite_collection_count = $rewrite_collection->count();
if($rewrite_collection_count < 0){
    foreach ($rewrite_collection->getItems() as $rewrite){
        $rewrite->delete();
    }
}

Mage::getModel('core/url_rewrite')
    ->setStoreId(1)
    ->setIsSystem(0)
    ->setOptions('RP')
    ->setIdPath($id_path)
    ->setRequestPath($request_path)
    ->setTargetPath($target_path)
    ->save();

2

Answers


  1. if($rewrite_collection_count < 0){
    

    The above code, only check the count is less than zero.

    Please change the code as

    if($rewrite_collection_count > 0){
        foreach ($rewrite_collection->getItems() as $rewrite){
            $rewrite->delete();
        }
    }
    
    Login or Signup to reply.
  2. Allow me to bring some ineteresting elements to the accepted answer, that you’ll be able to use for all your future delete/save operations :

    $transaction = Mage::getResourceModel('core/transaction');
    foreach ($rewrite_collection->getItems() as $rewrite){
        $transaction->addObject($rewrite);
    }
    $transaction->delete(); //or $transaction->save() when you need
    

    This allows you to delete/save all the objects you give to the transaction object to be saved/deleted in only one SQL transaction, and roll it back if an error occurs (automatically done if an exception is raised during the save of one of the models).

    Also, try to make a habit of calling your collections this way :

    $rewrite_collection = Mage::getResourceModel('core/url_rewrite_collection');
    

    instead of :

    $rewrite_collection = Mage::getModel('core/url_rewrite')->getCollection();
    

    Fewer steps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search