Programmatically: How to create custom Magento product attributes
Step 1: Create a new module
Create a new directory in the app/code/local directory, e.g., MyCompany/MyModule. Inside this directory, create the following files: etc/config.xml etc/system.xml Model/Setup.php
Step 2: Define the module configuration
In etc/config.xml, add the following code:
1.0.0
Step 3: Define the attribute setup
In etc/system.xml, add the following code:
\system xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/etc/system_config.xsd">
text
10
Step 4: Create the attribute setup script
In Model/Setup.php, add the following code:
namespace MyCompany\MyModule\Model;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Eav\Model\Entity\Attribute\Setup as EavSetup;
class Setup implements InstallDataInterface
{
private $eavSetup;
public function __construct(EavSetup $eavSetup)
{
$this->eavSetup = $eavSetup;
}
public function install(ModuleContextInterface $context)
{
$this->eavSetup->addAttribute(
\Magento\Catalog\Api\Data\ProductInterface::ENTITY_TYPE,
'my_custom_attribute',
[
'type' => 'text',
'label' => 'My Custom Attribute',
'input' => 'text',
'visible' => true,
'required' => false,
'user_defined' => true,
'sort_order' => 100,
]
);
}
}
Step 5: Register the setup script
In etc/module.xml, add the following code:
MyCompany_MyModule_Model_Setup
Step 6: Run the setup script
To run the setup script, navigate to the Magento admin panel and go to System > Tools > Dataflow > Run Wizard. Select "Run" and then "Yes" to execute the script.