Magento Adjust Sort Order of Already Added Product Attribute

In Magento you can add EAV product attributes (catalog_product) and sometimes it’s important the sort order of these fields. For example you may have a product setting for a field, and a global setting for a field, and you want the yes/no for global to be right next to the product setting. Here is code that you can use in your sql setup files to adjust the sort order:


$installer = new Mage_Catalog_Model_Resource_Setup('core_setup');
$installer->startSetup();
$attribute_model = Mage::getModel('eav/entity_attribute');
// product_field_name should be replaced with the product field sort order you want to adjust
$attribute_code = $attribute_model->getIdByCode('catalog_product', 'product_field_name');
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$table = $resource->getTableName('eav/entity_attribute');
// sort order you want the field to use
$newSortOrder = '20';
$query = "UPDATE {$table} SET sort_order = '{$newSortOrder}' WHERE attribute_id = "
. (int)$attribute_code;
$writeConnection->query($query);
$installer->endSetup();