octoxan
9/28/2016 - 1:01 PM

Magento 1.x getPriceRange Function

Magento 1.x getPriceRange Function

function getPriceRange($productId) {

	$max = '';
	$min = '';

	$pricesByAttributeValues = array();

	$product = Mage::getModel('catalog/product')->load($productId);
	$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
	$basePrice = $product->getFinalPrice();

	foreach ($attributes as $attribute) {
		$prices = $attribute->getPrices();
		foreach ($prices as $price) {
	    	if ($price['is_percent']){ //if the price is specified in percents
	        	$pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'] * $basePrice / 100;
	    	}
	    	else { //if the price is absolute value
	        	$pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'];
	    	}
		}
	}

	$simple = $product->getTypeInstance()->getUsedProducts();

 	foreach ($simple as $sProduct) {
    	$totalPrice = $basePrice;
	    foreach ($attributes as $attribute) {
	        $value = $sProduct->getData($attribute->getProductAttribute()->getAttributeCode());
	        if (isset($pricesByAttributeValues[$value])){
	            $totalPrice += $pricesByAttributeValues[$value];
	        }
	    }
	    if(!$max || $totalPrice > $max)
	        $max = $totalPrice;
	    if(!$min || $totalPrice < $min)
	        $min = $totalPrice;
 	}

	if ($min == $max) {
		return "$".$min;
	} else {
		return "$"."$min - "."$"."$max";
	}

}