Loop Through All Products in Category and Save Changes in Magento 1.9

categoryce-1.9.0.0collection;product

I need to loop through all the products in a particular category, change a custom attribute and then save each product.

Currently i have:

$_category = Mage::getModel('catalog/category')->load($_POST['id']);
$all_products = $_category->getProductCollection();

foreach ($all_products as $product) {
    $product = Mage::getModel('catalog/product')->load($product->getId());  
    $product->setCustomAttribute(xxxx);
    $product->save();
}

Is this best practice and can it be improved for performance? The collections average around 15-20 products in each and i am getting a very slow loadtime or even the script timing out.

I've used set_time_limit(0); to try and force it through but i imagine i can improve my code to stop me having to do this? Eventually the collections may have over 100-200 products each so need to find a good performance now

Best Answer

Instead of loading full product object use it resource model attribute save (getResource()->saveAttribute). It is quit quick awsy to save product data.

Set value: $product->setCustomAttribute('yourval');

Save it value using resource attribute

 $product->getResource()->saveAttribute($product, 'custom_attributte');

it only save this attribute not all attribute

Full code:

foreach ($all_products as $product) {
    $product->setCustomAttribute(xxxx);
    $product->getResource()->saveAttribute($product, 'custom_attributte');
}

if your value in array then implode()
$product->setCustomAttribute(implode(',',array()));

Related Topic