Configurable products in Magento 2 allow customers to choose from various options, such as different sizes or colors, making the shopping experience more dynamic and personalized. However, there are scenarios where you might want to pre-select certain options to guide the customer towards popular or recommended variants.
If you want to first option is selected of configurable product in Magento2 follow these steops:
1) Create a custom module:
Create registration.php file in app/code/BluethinkInc/FirstOptionSelected
1 2 3 4 5 6 7 8 9 10 11 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'BluethinkInc_FirstOptionSelected', __DIR__ ); |
Step 2) Create module.xml in app/code/BluethinkInc/FirstOptionSelected/etc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="BluethinkInc_FirstOptionSelected" setup_version="1.0.0"> <sequence> <module name="Magento_ConfigurableProduct"/> <module name="Magento_Swatches"/> </sequence> </module> </config> |
Step 3) Create requirejs-config.js in app/code/BluethinkInc/FirstOptionSelected/view/frontend
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var config = { map: { '*': { 'Magento_Swatches/js/swatch-renderer':'BluethinkInc_FirstOptionSelected/js/swatch-renderer' } } }; |
Step 4) Create swatch-renderer.js in
app/code/BluethinkInc/FirstOptionSelected/view/frontend/web/js/
Copy the code from vendor/magento/module_swatches/view/base/web/js/swatch-renderer.js
After that find this code $widget._EmulateSelected($widget._getSelectedAttributes());
and paste below code after $widget._EmulateSelected($widget._getSelectedAttributes());
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var swatchLength = $('.swatch-attribute').length; if(swatchLength >= 1){ if($('.swatch-attribute').hasClass("size")){ $('.swatch-option').first().trigger('click'); } } $('.swatch-option.color').first().click(); |
Then run these command:
php bin/magento se:s:d -f
php bin/magento c:f
Santosh Bharti
2024-06-20