I can't seem to figure out how to best update hundreds of category attributes with a script. Any suggestions as the best way to approach this? I won't be using the installer or anything like that.
2 Answers
If you have many categories and want to update few attributes than you can use code similar to this below. It's fast and saves only values for these attributes which you want to update. You can run this script from browser or from terminal (terminal is better for cases like you described).
<?php
require 'app/Mage.php';
Mage::app();
$resource = Mage::getResourceModel('catalog/category');
// here get category collection
foreach($collection as $category) {
$category->setStoreId(0); // 0 for default scope (All Store Views)
$category->setData('attribute_code', $value);
$resource->saveAttribute($category, 'attribute_code');
}
<?php
//increase the max execution time
@ini_set('max_execution_time', -1);
//memory_limit
@ini_set('memory_limit', -1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Start Despaly All Product Meta Title And Description
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$categories = Mage::getModel('catalog/category')
->getCollection()
// magic is prepared here..
->addAttributeToSelect('*')
// then the magic happens here:
->addAttributeToFilter('level', array('eq'=>4))
->load();
if (count($categories) > 0):
foreach($categories as $category):
$catId = $category->getId();
$category = Mage::getModel('catalog/category')->load($catId);
$resource = Mage::getResourceModel('catalog/category');
//if($catId==1465):
$CategoryName = $category->getName();
$metaTitle = "Buy ".$CategoryName." Meta Title";
$metaDescription = "Shop your favourite ".$CategoryName." Meta Description";
//$category->setMetaTitle($metaTitle);
//$category->setMetaDescription($metaDescription);
//$category->save();
$category->setData('meta_title', $metaTitle);
$resource->saveAttribute($category, 'meta_title');
$category->setData('meta_description', $metaDescription);
$resource->saveAttribute($category, 'meta_description');
$check = $category->getMetaTitle();
echo "<pre>";
print_r($catId);
echo "<pre>";
print_r($check);
echo "\n";
//endif;
endforeach;
else: echo "No Results";
endif;
?>`enter code here`