Get Price Range for Configurable Product in Magento 2

Hey everyone, few days back I got a requirement in which I need to display the Price Range of Configurable Product. I thought I will need to get all the associated products and then get the Minimum Price and Maximum Price. After some research in Magento Configurable Product Module I got a big lead. Luckily Magento provides the method for getting the Minimum and Maximum Price. In this Post we will see how we can get the Range in template file.

In your module structure create a layout file catalog_product_view_type_configurable.xml, in my case the file path is app/code/Webkul/PriceRange/view/base/layout/catalog_product_view_type_configurable.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.price">
            <block class="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable" name="wk.info.pricerange"  template="Webkul_PriceRange::product/price_range.phtml" />
        </referenceBlock>
    </body>
</page>

Now, we will create template file price_range.phtml at path app/code/Webkul/PriceRangeCustomisation/view/base/templates/

<?php
$currentProduct = $this->getProduct();
$regularPrice = $currentProduct->getPriceInfo()->getPrice('regular_price');
?>
<div class='price-box'>
    <span class="price">
        <?php
            echo $regularPrice->getMinRegularAmount().'-'.$regularPrice->getMaxRegularAmount();
        ?>
    </span>
</div>

Also, the methods getMinRegularAmount() and getMaxRegularAmount() returns the price of  In Stock associated products only. For further studying the method defination you can refer to the file

magento_root_directory/vendor/magento/module-configurable-product/Pricing/Price/ConfigurableRegularPrice.php

That’s all for the post, feedback is welcomed.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php