Categories
#DEV

Deleting Magento Customer Address Programmatically

When upgrading Magento for one of our customers, we’ve realized somehow all the shipping information were half complete. It either had a region filled out without address or zip code. When you enter that customer’s profile and try to save it, it wouldn’t save because these are required fields. This was causing these old customers to purchase stuff from the store because they assumed their address was saved.

The best thing to do when you encounter such an issue with Magento is to clear saved addresses altogether. Our team has written a neat little script that would delete all the saved addresses given that you know their email addresses. This is easy to find out if you were to just export all customer profiles through Magento panel. Some might argue that you can do this Data Profiles Import/Export function. Unfortunately, Magento has a function to replace only if the value contains something. If you leave it blank, it wouldn’t touch that field. So you would still have the customers whose addresses are half filled with missing information.

I hope this helps someone in need 🙂

<?php
  include('app/Mage.php');
  Mage::app();  
  
  $customer_emails = array(
    "[email protected]",
    "[email protected]"
);
  
  foreach($customer_emails as $customer_email){
    
    echo $customer_email . "</br>";
    $customer = Mage::getModel("customer/customer");
    $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
    $customer->loadByEmail($customer_email); //load customer by email id
    $customer_id = $customer->getId();
    
      echo $customer_id. "</br>";
      foreach ($customer->getAddresses() as $address)
      {
         $customerAddress[] = $address->toArray();
         
         $address->delete();
      }
      
    echo '<pre/>';print_r($customerAddress );
  }
  
  
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *