Magento – How to show visual swatch color on product listing page magento2

color-swatchesmagento2product-attributeproduct-list

Hi i am trying to show the color on product listing page which is configure in the color attribute as visual swatch.

Please find the screenshot below.

enter image description here

Best Answer

<?php/***********Display Color Attribute************/?>
<?php
$om = \Magento\Framework\App\ObjectManager::getInstance();
$attribute = $om->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class)->get('color');
?>
<ul>
<?php
foreach ($attribute->getOptions() as $option) {
    $name = $option->getLabel();
    $optId = $option->getValue();
    $curnt_cat_url = $category->getUrl();
    $colorId = '?color='.$optId;

    $swatchHelper=$om->get("Magento\Swatches\Helper\Media");
    $swatchCollection = $om->create('Magento\Swatches\Model\ResourceModel\Swatch\Collection');
    $swatchCollection->addFieldtoFilter('option_id',$optId);
    $item=$swatchCollection->getFirstItem();
    $ThumbImage =  $swatchHelper->getSwatchAttributeImage('swatch_thumb', $item->getValue());
    //$SwatchImage = $swatchHelper->getSwatchAttributeImage('swatch_image', $item->getValue());
?>
    <?php if ($ThumbImage) { ?>
        <div class="color_bg">
            <li class="color_img_bg"> 
                <a href="<?php echo $curnt_cat_url.$colorId ?>"><img src="<?php echo $ThumbImage; ?>"></a>
            </li>
        </div>
    <?php } ?>
<?php } ?>
</ul>
Related Topic