Hey if you using Magento 2 then
add below function in your custom helper class
public function addAttributeToAllAttributeSets($attributeCode,$attributeGroupCode) {
$entityType = $this->eavTypeFactory->create()->loadByCode('catalog_product');
$attribute = $this->attributeFactory->create()->loadByCode($entityType->getId(), $attributeCode);
if (!$attribute->getId()) {
return false;
}
/** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection $setCollection */
$setCollection = $this->attributeSetFactory->create()->getCollection();
$setCollection->addFieldToFilter('entity_type_id', $entityType->getId());
/** @var Set $attributeSet */
foreach ($setCollection as $attributeSet) {
/** @var Group $group */
$group = $this->attributeGroupFactory->create()->getCollection()
->addFieldToFilter('attribute_group_code', ['eq' => $attributeGroupCode])
->addFieldToFilter('attribute_set_id', ['eq' => $attributeSet->getId()])
->getFirstItem();
$groupId = $group->getId() ? : $attributeSet->getDefaultGroupId();
// Assign:
$this->attributeManagement->assign(
'catalog_product', $attributeSet->getId(), $groupId, $attributeCode, $attributeSet->getCollection()->count() * 10
);
}
return true;
}
and for this construct function to create objects will be
public function __construct(
AttributeFactory $attributeFactory,
SetFactory $attributeSetFactory,
CatalogtransporterFactory $catalogTransporterFactory,
GroupFactory $attributeGroupFactory,
TypeFactory $typeFactory,
AttributeManagement $attributeManagement,
Context $context,
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Eav\Attribute $cattributeFactory,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Eav\Model\AttributeRepository $attributeRepository,
\Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
\Magento\Eav\Api\Data\AttributeOptionLabelInterface $attributeOptionLabel,
\Magento\Eav\Model\Entity\Attribute\Option $option
) {
$this->attributeFactory = $attributeFactory;
$this->attributeSetFactory = $attributeSetFactory;
$this->catalogTransporterFactory = $catalogTransporterFactory;
$this->eavTypeFactory = $typeFactory;
$this->attributeGroupFactory = $attributeGroupFactory;
$this->attributeManagement = $attributeManagement;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_storeManager = $storeManager;
$this->eavConfig = $eavConfig;
$this->_cattributeFactory = $cattributeFactory;
$this->_attributeRepository = $attributeRepository;
$this->_attributeOptionManagement = $attributeOptionManagement;
$this->_option = $option;
$this->_attributeOptionLabel = $attributeOptionLabel;
parent::__construct($context);
}
And then call same function
$helper = $this->_objectManager->create('\Companyname\Modulename\Helper\Data');
$helper->addAttributeToAllAttributeSets('attribute_code','general');