Magento – Magento 2 Product Attribute Swatch Image

attributesmagento2

I have created a product attribute that is using an image swatch for each attribute value.

My question is how can I go about retrieving the image swatch URL from the attribute within my product view?

I am familiar with how to retrieve an attribute value but can't seem to figure out how to retrieve the image swatch.

Any help would be great.

Best Answer

To retrieve that value, you need the next in your block or viewModel (https://www.yireo.com/blog/1856-viewmodels-in-magento-2)

...

use Magento\Catalog\Helper\Data as CatalogData;
use Magento\Swatches\Helper\Data;
use Magento\Swatches\Helper\Media;

...

/**
 * @var Data
 */
private $swatchesHelper;

/**
 * @var Media
 */
private $swatchesHelperMedia;

/**
 * @var CatalogData
 */
private $catalogHelperData;

...

/**
 * @return string|null
 */
public function getSwatchImage()
{
    $product = $this->catalogHelperData->getProduct(); //This depends of as you want do it,but you can do it on this way
    if ($product->getSwatchAttribute()) {
        $image = $this->swatchesHelper->getSwatchesByOptionsId([$product->getSwatchAttribute()]);
        if (current($image)['value']) {
            return $this->swatchesHelperMedia->getSwatchAttributeImage('swatch_thumb', current($image)['value']);
        }
    }

    return null;
}

swatch_attribute is the attribute code.