Magento 2. Add price to swatches.

by Peter D.

Adding prices to Magento swatches will help users to update product price via swatches. Custom color swatches aim to improve the shopping experience in your store.

With the Argento possibility to create a custom theme, it will be easy for you to add JS code to display swatch options.

First, you have to create Argento-custom.js. Look at steps on how to add custom js.

Then you will have to add the following javascript code:

define([
    'jquery',
    'underscore',
    'priceUtils',
    'domReady!'
], function($, _, priceUtils) {

    function addPricesToOptions() {
        if (!$('[data-role=swatch-options]').first().data('mageSwatchRenderer')) {
            return setTimeout(addPricesToOptions, 500);
        }

        var config = $('[data-role=swatch-options]').first()
                .data('mageSwatchRenderer').options.jsonConfig;

        $('.swatch-attribute').each(function () {
            var attributeId = $(this).attr('attribute-id');
            $('.swatch-option', this).each(function () {
                var optiondId = $(this).attr('option-id');
                var index = _.findKey(config.index, function(value) {
                    return value[attributeId] == optiondId;
                });
                this.innerHTML += ' <span class="price">' +
                    priceUtils.formatPrice(
                        config.optionPrices[index].finalPrice.amount,
                        config.priceFormat
                    ) +
                    '</span>';
            });
        });
    }

    if ($('[data-role=swatch-options]').length) {
        addPricesToOptions();
    }
});

At the end, you have to make static content redeploy:

php bin/magento setup:static-content:deploy

Recent articles