Magento 2

How to Set Product-wise swatches in Magento 2

We love shopping when choosing product options becomes much easier like color and size option. Swatches provide an alternate way to display the selection of options just by clicking for configurable products rather than choosing an option from typical drop-down options. Also, a few days back we have written a blog on “How to use Configurable Swatches in our Custom Magento Theme” where w, these swatches are only available for the default package. But we provide code through which you can add this feature in your custom theme.
But there is one problem when you create swatches from the product Magento creates global swatches for all the products that create a bad impression on your customers as shown below.

So, we are back with a small piece of code that allows you to set product-wise swatches in your Magento 2 store.
First create “Di.xml” file inside etc folder using below code.
app\code\Vendor\Extension\etc

<pre class="lang:default decode:true">
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Swatches\Block\Product\Renderer\Configurable" type="Vendor\Extension\Block\Product\Configswatch" />
</config>
</pre>

Now Create New Block file name Configswatch.php At this path and add below code to that file.
app\code\Vendor\Extension\Block\Product

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Block\Product;

class Configswatch extends \Magento\Swatches\Block\Product\Renderer\Configurable
{
    protected $_storeManager;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    )
    {
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);
    }
    public function getJsonSwatchConfig()
    {
        $attributesData = $this->getSwatchAttributesData();
        $allOptionIds = $this->getConfigurableOptionsIds($attributesData);
        $swatchesData = $this->swatchHelper->getSwatchesByOptionsId($allOptionIds);

        $config = [];
        foreach ($attributesData as $attributeId => $attributeDataArray) {
            if (isset($attributeDataArray['options'])) {
                $config[$attributeId] = $this->addSwatchDataForAttribute(
                    $attributeDataArray['options'],
                    $swatchesData,
                    $attributeDataArray,
                    $attributeId
                );
            }
        }

        return $this->jsonEncoder->encode($config);
    }
    protected function addSwatchDataForAttribute(
        array $options,
        array $swatchesCollectionArray,
        array $attributeDataArray,
        $attributeId=null
    ) {

        $currentStore = $this->_storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'/customswatch/';

        $result = [];
        foreach ($options as $optionId => $label) {
            if (isset($swatchesCollectionArray[$optionId])) {
                $result[$optionId] = $this->extractNecessarySwatchData($swatchesCollectionArray[$optionId]);
                $result[$optionId] = $this->addAdditionalMediaData($result[$optionId], $optionId, $attributeDataArray);
                $result[$optionId]['label'] = $label;
                if ($attributeId) {
                    if($this->getProduct()->getId()==2 && $attributeId == 10) {
                        if($optionId == 5) {
                            $result[$optionId]['type'] = 2; // Option Type is Image
                            $result[$optionId]['value'] = $mediaUrl.'blue-jeans.jpg';
                            $result[$optionId]['thumb'] = $mediaUrl.'blue-jeans.jpg';
                        } elseif ($optionId == 6) {
                            $result[$optionId]['type'] = 2; // Option Type is Image
                            $result[$optionId]['value'] = $mediaUrl.'green-jeans.jpg';
                            $result[$optionId]['thumb'] = $mediaUrl.'green-jeans.jpg';
                        }
                    }
                }
            }
        }

        return $result;
    }
}
</pre>

That’s it for today, Let us know if you are facing an issue while implementing swatches using this code by commenting below.

Happy Swatches!

Click to rate this post!
[Total: 4 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 day ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

7 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

7 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago