Magento – How To get Visual Swatch attribute image path in magento2

magento2

I created one attribute with type Visual Swatch

now i need to get image path of specific option value or product then how to get it ?

Best Answer

I had the same problem. Finaly got it working with below code:

use Magento\Swatches\Helper\Data as SwatchData;
use Magento\Swatches\Helper\Media;

...

public function __construct(
    SwatchData $swatchHelper,
    Media $swatchMediaHelper,
    Config $eavConfig
) {

    $this->eavConfig = $eavConfig;
    $this->swatchHelper = $swatchHelper;
    $this->swatchMediaHelper = $swatchMediaHelper;
}

...

$attribute = $this->eavConfig->getAttribute('catalog_product',         
$attribute_code); //First get the current attribute
$options = $attribute->getSource()->getAllOptions();

//Get all value_id's from attribute and add them to a array
$valueIds = [];

foreach ( $options as $option ) {
    $valueIds[] = $option['value'];
}
//Get all images for value_id's
$images = $this->swatchHelper->getSwatchesByOptionsId($valueIds);

Now $images contains an array with the id, label and image for each value.

Hope this helps someone.

Related Topic