This article describe it step by step:
http://www.extensions.sashas.org/blog/magento-2-make-customer-attribute.html
The main part is DataInstall::install method:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, '{attributeCode}', [
'type' => 'varchar',
'label' => '{attributeLabel}',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
//add attribute to attribute set
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
Or a bit slighter:
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'nickname',
[
'label' => 'Nickname',
'required' => 0,
'system' => 0,
'position' => 100
]
);
$customerSetup->getEavConfig()->getAttribute('customer', 'nickname')
->setData('used_in_forms', ['adminhtml_customer'])
->save();
Also here is nice article:
https://www.atwix.com/magento/adding-attribute-programatically-magento2/