Magento 2 – Get Configurable Option and Its Price

configurable-productmagento2price

I am trying to pull configurable products option and price on product detail page on seprate section. on radio button. I've used below code to get detail of options but i can retrive price of options.

$blockObj = $block->getLayout()->createBlock('Magento\ConfigurableProduct\Block\Product\View\Type\Configurable');


$_attributes = $blockObj->decorateArray($blockObj->getAllowAttributes());

 foreach ($_attributes as $_attribute): ?>

    <?php foreach ($_attribute->getData('options') as $option):    ?>
        // option detail here
     <?php endforeach; ?>
 <?php endforeach; ?>

I've also try to get product id of options but i can get in above data. anyone have idea. how to get it?
Note: I've used objectmanager for testing now. I'll use class to use once my code will be ready

Best Answer

This code tested on Magento 2.1.4.

All you need is in getConfigurableOptions call.

67 - is a test product ID. In my installation that is a configurable product id. Change it to your product id.

Copy paste it to testfile.php and run php config.php inside magento root:

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$repository = $obj->create('Magento\Catalog\Model\ProductRepository');
$product = $repository->getById('67');

$data = $product->getTypeInstance()->getConfigurableOptions($product);

$options = array();

foreach($data as $attr){
  foreach($attr as $p){
    $options[$p['sku']][$p['attribute_code']] = $p['option_title'];
  }
}


foreach($options as $sku =>$d){
  $pr = $repository->get($sku);
  foreach($d as $k => $v)
    echo $k.' - '.$v.' ';
  echo ' : '.$pr->getPrice()."\n";
}

Here is the output: enter image description here

Related Topic