Variant on Shop Page – Click it will open product detail and pre-selected variant option

To add Variant on Shop Page.

and make it pre-selected on click from shop page.

You can use this code to Store Page Header Injection

<!-- tuanphan - variant pre-selected - 21-09-2025 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>$(document).ready(function(){$('.product-list-item').each(function(){var $productItem=$(this);var productId=$productItem.data('product-id');var productLink=$productItem.find('.product-list-item-link').attr('href');if(productId&&productLink){var jsonUrl=productLink+'?format=json-pretty';$.ajax({url:jsonUrl,method:'GET',success:function(data){var variants=data.item.variants;var variantOptionOrdering=data.item.variantOptionOrdering;if(variants&&variants.length>0&&variantOptionOrdering&&variantOptionOrdering.length>0){var variantOptionsHtml='<div class="variant-options">';variantOptionOrdering.forEach(function(optionName){var uniqueValues=[];variants.forEach(function(variant){var value=variant.attributes[optionName];if(value&&uniqueValues.indexOf(value)===-1){uniqueValues.push(value)}});if(uniqueValues.length>0){uniqueValues.forEach(function(value){variantOptionsHtml+='<span class="variant-option" data-option-name="'+optionName+'" data-option-value="'+value+'">'+value+'</span>'})}});variantOptionsHtml+='</div>';$productItem.find('.product-list-item-meta').after(variantOptionsHtml)}},error:function(){console.log('Không thể lấy thông tin variants cho product: '+productId)}})}});$(document).on('click','.variant-option',function(e){e.preventDefault();e.stopPropagation();var $variantOption=$(this);var $productItem=$variantOption.closest('.product-list-item');var productLink=$productItem.find('.product-list-item-link').attr('href');var optionName=$variantOption.data('option-name');var optionValue=$variantOption.data('option-value');if(productLink){var url=new URL(window.location.origin+productLink);url.searchParams.set('variant-'+optionName.toLowerCase(),optionValue);window.location.href=url.toString()}});if(window.location.pathname.includes('/store/p/')){var urlParams=new URLSearchParams(window.location.search);urlParams.forEach(function(value,key){if(key.startsWith('variant-')){var optionName=key.replace('variant-','');var capitalizedOptionName=optionName.charAt(0).toUpperCase()+optionName.slice(1);var $select=$('select[name="variant-option-'+capitalizedOptionName+'-select"]');if($select.length>0){$select.val(value);$select.removeClass('show-placeholder');$select.closest('.variant-select-wrapper').attr('data-selected-value',value)}}})}});</script>
<style>
div.product-list-item span.variant-option{border:1px solid #000;padding:5px 10px;display:inline-block;margin-bottom:10px;margin-left:5px;margin-right:5px}
</style>
You need to login to see the full content. Or send me an email to [email protected], I will send you code.
Buy me a coffee