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

4
  • Do you have a filter to determine if a value is unused or used? Or this is what you are asking. Commented Feb 15, 2018 at 12:34
  • I have updated my question, does that help?
    – Goose84
    Commented Feb 15, 2018 at 12:36
  • How many products do you have? what do you mean, values connected to it? How did you identified these 100 different values? Commented Feb 15, 2018 at 12:38
  • Around 750 products
    – Goose84
    Commented Feb 15, 2018 at 12:39

1 Answer 1

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);
    
2
  • Thanks for the answer but then how would I delete them as your code would only find the ones not used
    – Goose84
    Commented Feb 15, 2018 at 13:22
  • well once you have the unused options you can delete them. You can do it programmatically as suggested magento.stackexchange.com/questions/126213/… 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
    Commented Feb 15, 2018 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.