3

Is it possible to remove any unused product attribute values? All the answer I find seem to be related to magento 1 and not 2.

I have a product attribute called size and it has around 100 different values connected to it. However I am not sure which ones are used and which ones are not. Therefore I would like to run a script or a sql statement to run to remove all of the ones which aren't connected to any products

Goose84
  • 2,601
  • 2
  • 28
  • 61

1 Answers1

1

I think you could to it with a small extension like:

  • get all products with something like:

    $products = $this->_productCollectionFactory->create()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('your_attr', array('neq' => ''));
    
  • save in an array all the option values of your custom attribute from all the products

    $my_custom_attribute_values = []; 
    foreach($products as $p) {   
       array_push($my_custom_attribute_values, $p->yor_attr); 
    }
    
  • get all possible attribute values, something like:

    $attribute = $this->eavConfig->getAttribute('catalog_product', 'your_attribute_code');
    $options = $attribute->getSource()->getAllOptions();
    foreach($options as $opt){
        array_push($option_values, $opt->value);
    }
    
  • diff the two arrays:

    array_diff($option_values, $my_custom_attribute_values);
    
Pankaj Pareek
  • 3,556
  • 3
  • 23
  • 46
sissy
  • 534
  • 1
  • 8
  • 24
  • Thanks for the answer but then how would I delete them as your code would only find the ones not used – Goose84 Feb 15 '18 at 13:22
  • well once you have the unused options you can delete them. You can do it programmatically as suggested https://magento.stackexchange.com/questions/126213/programatically-delete-custom-attribute-options here for example, you can use REST API... it's up to you to complete the code, this is just a flow you could follow. – sissy Feb 15 '18 at 13:32