Create attribute options magento 2

This tutorial explains how to create attribute options magento 2 programmatically. Please click here to refer the tutorial that read data from the options.csv file and compare with existing attribute options.

Then create the attribute options as shown below.Please click here for detailed explanation and other magento 2 tutorial.

Create attribute options magento 2
create-attribute-options-magento-2-programmatically

// add new attribute options
function addNewOptions( $object_Manager, $newOptions, $storeArray ) {
    
    $option = array();
    $eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
    $attribute = $eavConfig->getAttribute('catalog_product', 'color');
    $option['attribute_id'] = $attribute->getAttributeId();
    
    foreach($newOptions as $key => $value){
        
        $option['value'][$value][0]=$value;
        
        foreach($storeArray as $storeKey => $store) {
            $option['value'][$value][$storeKey] = $value;
        }   
        echo 'Added value : '.$value.PHP_EOL;
    }
 
    $eavSetup = $object_Manager->get('\Magento\Eav\Setup\EavSetup');
    $eavSetup->addAttributeOption($option);
}

// Compare with Existing options

function cmpOptions( $optionsValues, $optionsExists ) {
  
    $newOptions = array_diff( $optionsValues, $optionsExists );
    return $newOptions;
    
}

// Get all stores

function getAllStores( $object_Manager ) {
    $storeManager = $object_Manager->get('Magento\Store\Model\StoreManagerInterface');
    $stores = $storeManager->getStores();
    $storeArray[0] = "All Store Views";       

    foreach ($stores  as $store) {
        $storeArray[$store->getId()] = $store->getName();
    }
    return $storeArray;
}

Share this Tutorial