Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Custom Option Values of a product magento 2

I have two custom options for a product. Color and Size and both are dropdowns. In product detail pages, I have to display all available colors of that product.

I tried the following code and it works. But it returns all the values of Color and Size. But I only need the color values. That is I want to select the custom options by color.

$_product = $block->getProduct();

foreach($_product->getOptions() as $o){
  foreach($o->getValues() as $value){
    print_r($value->getData());
  }
}
like image 615
Arun SS Avatar asked Oct 19 '22 05:10

Arun SS


1 Answers

I don't know if you still need it or not, but i found a solution.

foreach($product->getProductOptionsCollection() as $o){
     foreach($o->getValues() as $ov){
        // do whatever you want to it;
        var_dump($ov->getData());
    }
}

The dump will return something like this, without all the NULLs ( this is an imported product )

array(13) {
  ["option_type_id"]=>
  string(5) "23122"
  ["option_id"]=>
  string(4) "6045"
  ["sku"]=>
  string(1) "2"
  ["sort_order"]=>
  string(1) "2"
  ["default_title"]=>
  string(33) "Test Option"
  ["store_title"]=>
  NULL
  ["title"]=>
  string(33) "Test Option"
  ["default_price"]=>
  NULL
  ["default_price_type"]=>
  NULL
  ["store_price"]=>
  NULL
  ["store_price_type"]=>
  NULL
  ["price"]=>
  NULL
  ["price_type"]=>
  NULL
}
like image 197
Radosav227 Avatar answered Oct 27 '22 12:10

Radosav227