photo credit: Jelly Beans via photopin (license)

Magento 2 : Add a product attribute to all attribute sets programmatically

When a Magento 2 shops grows, it gains more and more attribute sets. Adding new attributes to all attribute sets might become a cumbersome task. Especially when you first have to do it on your local development environment, and once again for your test- and production environments. Seems not very DRY to me. So why not automate this?


Magento 2 has a nifty little class that can help you with this task: Magento\Eav\Model\AttributeManagement . This class has a cool little assign() -method (and also a unassign() -method for that matter) that does a lot of heavy number crunching for you. Just look at it’s signature:

This is one part of the code, but most likely the part you were looking for. Since all other stuff can be easily calculated with all the factories Magento 2 provides. But in case you want the full monty:

That’s it! One script to add a single attribute to all attribute sets at once.

Visitors give this article an average rating of 3.4 out of 5.

How would you rate this article?

3 thoughts on “Magento 2 : Add a product attribute to all attribute sets programmatically”

  1. Rabot says:

    It would be fine if we have also the “use” for classes…

  2. Alex says:

    This article has no sense without “use” !!!!!

  3. Alex says:

    Finally I figured out full classes:

    use Magento\Eav\Model\Entity\Attribute;
    use Magento\Eav\Model\Entity\AttributeFactory;
    use Magento\Eav\Model\AttributeManagement;
    use Magento\Eav\Model\Entity\Attribute\Group;
    use Magento\Eav\Model\Entity\Attribute\GroupFactory;
    use Magento\Eav\Model\Entity\Attribute\Set;
    use Magento\Eav\Model\Entity\Attribute\SetFactory;
    use Magento\Eav\Model\Entity\TypeFactory;

Leave a Reply to Alex Cancel reply