You’re developing a Magento importer and you want to clean your DB after some tests? Here you have:
require_once dirname(__FILE__) . '/app/Mage.php'; Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID)); $resource = Mage::getSingleton('core/resource'); $db_read = $resource->getConnection('core_read'); $categories = $db_read->fetchCol("SELECT entity_id FROM " . $resource->getTableName("catalog_category_entity") . " WHERE entity_id>1 ORDER BY entity_id DESC"); foreach ($categories as $category_id) { try { Mage::getModel("catalog/category")->load($category_id)->delete(); } catch (Exception $e) { echo $e->getMessage() . "\n"; } }
Great snippet, thank you, I am pruning the categories on csv import and this is very useful.
Just to let you now that you should not delete default category entities, at least not the Default Category which has id=2 on catalog_category_entity. This breaks the UI on catalog admin.
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
foreach(Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('entity_id', array('gt' => 2)) as $cat) {
$cat->delete();
}