Here is a quick code to delete customers programmatically in Magento. You can manually delete customers from customer admin grid. But, sometime you might need to do it automatically through code.
Here is the full code to do so. This code can be saved in a new file in your Magento root folder and then you can run it in browser.
In this code, I have selected customers created within a certain date range. And then deleted those selected customers individually.
/**
* Delete Customers
*
*/
require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);
$dateFrom = '01/01/2015';
$dateTo = '30/01/2015';
$fromDate = Mage::app()->getLocale()->date($dateFrom)->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$toDate = Mage::app()->getLocale()->date($dateTo)->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$customerCollection = Mage::getModel('customer/customer')->getCollection()
->addAttributeToFilter('created_at', array('date' => true, 'from' => $fromDate))
->addAttributeToFilter('created_at', array('date' => true, 'to' => $toDate));
# $customerCollection->printLogQuery(true);
$customerIds = array();
foreach ($customerCollection as $customer) {
$customerIds[] = $customer->getEntityId();
}
$customerCollectionNew = Mage::getModel('customer/customer')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $customerIds))
if ($customerCollectionNew->count()) {
foreach ($customerCollectionNew as $customer) {
try {
$id = $customer->getId();
$customer->delete();
echo 'Customer '.$id.' is deleted.<br/>';
Mage::log('Customer '.$id.' is deleted.<br/>', null, "customer-delete.log");
} catch (Exception $e) {
echo "Customer ".$id." is deleted: " . $e->getMessage() . '<br/>';
Mage::log("Customer ".$id." could not be removed: " . $e->getMessage(), null, "customer-delete.log");
}
}
echo "<br>";
echo "Completed.";
Mage::log("Completed.", null, "customer-delete.log");
}
Hope this helps.
Thanks.