CommercePeer Brand Logo


Programmatically: Magento 2 Product Entity

Programmatically: How to create custom Magento category attributes

Step 1: Create a new attribute

Create a new file CustomCategoryAttribute.php in the app/code/local/YourCompany/YourModule/Model directory (replace YourCompany and YourModule with your actual module name).


	namespace YourCompany\YourModule\Model;

	class CustomCategoryAttribute extends Mage_Catalog_Model_Entity_Attribute_Abstract
  {
    public function _construct()
    {
        parent::_construct();
        $this->_elementType = 'category';
    }
  }
	

Step 2: Define the attribute's properties

Create a new file attribute.xml in the app/etc/modules/YourCompany_YourModule/etc directory.


		
	
    
        
            true
            local
        
    
    
        
            
                
                    
                    Your Custom Category Attribute
                    text
                    text
                    store
                    1
                    0
                
            
        
    
	
	

In this file, we're defining the attribute's properties:

label: the attribute's label frontend_label: the label displayed in the admin interface type: the type of input field (in this case, a text field) input_type: the type of input field (in this case, a text field) global_scope: the scope of the attribute (in this case, store-wide) visible: whether the attribute is visible or not required: whether the attribute is required or not

Step 3: Save the attribute

Run the following command in your terminal:


		php bin/magento setup:upgrade
		php bin/magento setup:static-content:deploy
	

Step 4: Add the attribute to a category

You can now add this custom attribute to a category programmatically using the following code:


		$category = Mage::getModel('catalog/category');
		$category->load(1); // load category ID 1

		$attribute = Mage::getResourceSingleton('catalog/category')->getAttribute('yourcompany_yourmodule_custom_category_attribute');
		$category->addAttributeToEntity($attribute);

		$attributeValue = 'Test value';
		$category->setData($attributeValue);
		$category->save();
	

LET’S WORK TOGETHER

We love working with Small Businesses, Retailers, Manufacturers. Our team is here to Help.

→ Schedule Free Consultant Now
Copyright © 2024 CommercePeer. All Rights Reserved.