Magento2 How to get configurable option and its price?
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:
Please try below code to get child product object.
$_children = $_product->getTypeInstance()->getUsedProducts($_product);
foreach ($_children as $child){
$logger->info("Here are your child Product Ids ".$child->getID());
}
Hope this will help you.