Magento 2 – How to Get Attribute Value of Child Configurable Products

attributesconfigurable-productdimensionsmagento2

I have this situation:

I have many configurable products with child products(the same product but with different variations).
Here are the variations that I mean

enter image description here

What I need to do is just to get the dimensions of the variations (weight, length, height and width).
If I do this I get 0, because the main product has no height in it's attributes, and also the attribute height is not showing in the main product, so I cannot set a height.

$height += $product->getData('ts_dimensions_height'); 

How can I set dimensions to the main product, or how can I get the attributes of the variation products?

Note: I cannot do a foreach array in the variations of the configurable product, because I'm adding up all dimensions depending on the amount of the products. For example If I have Product A with child product 2 and Product B with child product 1 I need to add up the dimensions, just like this:

foreach ($orderItems as $item) {

             $product = $item->getProduct();

                $weight += (float) ($product->getData('weight')*$item->getQty());
                $height += (float) ($product->getData('ts_dimensions_height')*$item->getQty()); 
                $length += (float) $product->getData('ts_dimensions_length');
                $width += (float) $product->getData('ts_dimensions_width');  


         }

Greetings!

Best Answer

In this case, you need to get the child item. You can use below code to get child item detail and add your logic:

 foreach( $orderItems as $item){ 
    if ($item->getProductType()=="configurable") { 
        foreach( $item->getChildrenItems() as $chitem){
             // child product
            echo $chitem->getSku(); 
        } 
    } else {
        // simple product
    }
}