Tag Archives: Paging

Clearing and Setting Attributes in Magento Programatically

Todays challenge following a 4000 product import from a supplier into a Magento store was to set all the Categories in the store to Anchor and to clear down the Meta_Title, Meta_Description and Meta_Keywords attributes within magento, that had been loaded with rubbish during the Import.

To do this manually even using the update attributes script inside the product editor of Magento would have been a total pain so a quick script was need in PHP using the core Mage functions to do this programatically, especially as this is to be an ongoing task which will need to be run after each import so ideally a PHP script file that can be set to run as a cron job is ideal.

The following script worked a treat, using paging on the product collections to keep the memory usage down to a minimum during running.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Load Up Magento Core
define('MAGENTO', realpath(''));

require_once(MAGENTO . '/app/Mage.php');

$app = Mage::app();

$categories = Mage::getModel('catalog/category')
  ->getCollection()
  ->addAttributeToSelect('*')
  ->addAttributeToFilter('is_anchor', 0)
  ->addAttributeToFilter('entity_id', array("gt" => 1))
  ->setOrder('entity_id')
;

foreach($categories as $category) {
echo $category->getId() . "\t" . $category->getName() . "</br>";
  $category->setIsAnchor(1);
  $category->save();
}

$productCollection = Mage::getModel('catalog/product')
  ->getCollection()
  ->addAttributeToSelect('sku')
  ->addAttributeToSelect('meta_title')
  ->addAttributeToSelect('meta_description')
  ->addAttributeToSelect('meta_keywords')
  ->setPageSize(10)
;

for($page = 1; $page <= $productCollection->getLastPageNumber(); $page++)
{
  $productCollection->clear()->setCurPage($page)->load();
  foreach($productCollection as $product) {
    echo $product->getId() . "\t" . $product->getSku() . "</br>";
    $product->setMetaDescription('');
    $product->setMetaTitle('');
    $product->setMetaKeywords('');
    $product->save();
  }
}

?>

But please please please please please remember, before running anything like this, take a backup of your data, unless you are 120% confident that the script will do what exactly what you want it to do, and even then, take a backup just in case.