Magento – Set default value to custom attribute for all products

I have created the custom attribute (test) for products as a text field with default value('test') from admin panel

And assign that attribute to default attribute set.

Now I can able to see the new custom attribute in product edit page.

When I try to filter with the product collection

Mage::getModel('catalog/product')->getCollection()
       ->addAttributeToSelect('*')
       ->addAttributeToFilter('test', array('like' => 'test'))->getData();

It returns the empty array.

==> The problem is existing products have an empty value, it will use the default value of the new attribute, so you need to use a script to update a value of the new attribute for all products. Here is how to do:

$attrData = array(
    'attribute_code_here'=> 'Default Value Here',
);
$storeId = 0;
$productIds = Mage::getModel('catalog/product')->getCollection()->getAllIds();
Mage::getModel("catalog/product_action")->updateAttributes(
    $productIds, 
    $attrData, 
    $storeId
);

Revisions

No comments yet.

Leave a Reply