Tags/topics: 
1
Answers
Vote up!
1
Vote down!

Get product image from product object

I am new to Drupal Commerce and having problem in retrieving product image from product object. I am doing commerce_product_load(product_id) for getting product object. Although I have stored image while creating the product but still the field_image array is empty.

I tried to get product object in two ways:
First, using line item wrapper I retrieved every line item object and using the line item object I retrieved product ids and finally their product object. In this case the field_image array was not empty.

Second, I used commerce_line_item_load(line item id) to create a line item object and retrieved product id from the line item object. Finally product object from product id. In this case field_image array was empty.

Does product object also depends on the line item object? Do I always have to load product object from line object obtained from line item wrapper?

Subhojit Paul
Asked by: Subhojit Paul
on November 13, 2012

1 Answer

Vote up!
1
Vote down!

The following code gave me access to an image for my product:

<?php
$product
= commerce_product_load_by_sku('PROD-01');
dpm($product);
?>

But it occurs to me that you may need to find an image attached to the product display?

<?php
$product
= commerce_product_load_by_sku('PROD-01');
dpm($product);

// Find all nodes that reference this product
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->
propertyCondition('status', 1)
  ->
fieldCondition('field_product', 'product_id', $product->product_id, '=');

$result = $query->execute();

if (isset(
$result['node'])) {
 
$product_nodes = entity_load('node', array_keys($result['node']));
  foreach (
$product_nodes as $product_node) {
   
dpm('<img src="'.image_style_url('medium', $product_node->field_image['und'][0]['filename']).'" />');
  }
}
?>
Josh Miller
Answer by: Josh Miller
Posted: Mar 6, 2013