Skip to main content

Programmatically Assign Attribute to All Attribute Sets in Magento 2

I will put here the way to add an attribute group then assign an attribute into all attribute set with this group, please note I am using the dirty way to add it so you will need to follow the Dependency injection in your code to have the same result 


$objectManager = $this->objectManager ;
/* Attribute assign logic */
$eavSetup = $objectManager->create(\Magento\Eav\Setup\EavSetup::class);
$config = $objectManager->get(\Magento\Catalog\Model\Config::class);
$attributeManagement = $objectManager->get(\Magento\Eav\Api\AttributeManagementInterface::class);

$entityTypeId = $eavSetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
$attributeSetIds = $eavSetup->getAllAttributeSetIds($entityTypeId);

$categorySetupFactory = $objectManager->get('\Magento\Catalog\Setup\CategorySetupFactory');
$setup = $objectManager->get('\Magento\Framework\Setup\ModuleDataSetupInterface');
$categorySetup = $categorySetupFactory->create(['setup' => $setup]);

foreach ($attributeSetIds as $attributeSetId) {
    if ($attributeSetId) {

        $group_id = $config->getAttributeGroupId($attributeSetId, "Attributes");

        if(!$group_id) {
            $categorySetup->addAttributeGroup(
                \Magento\Catalog\Model\Product::ENTITY,
                $attributeSetId,
                "Attributes", // attribute group name
                17 // sort order
            );
            //echo $attributeSetId . " - ".$group_id.'<br>';
            $group_id = $config->getAttributeGroupId($attributeSetId, "Attributes");
        }

        $attributeManagement->assign(
            'catalog_product',
            $attributeSetId,
            $group_id,
            "{attribute_code}",
            100
        );
    }