Create Product Display and Product


Create Product Display and Product Programmatically using Metadata Wrappers with Drupal Commerce

Get raw version
  1. global $user; // probably not the best idea, but great "just works" example code
  3. // Create a Product
  4. // thanks
  5. $product = entity_metadata_wrapper('commerce_product', commerce_product_new('product'));
  6. $product->title = 'my title';
  7. $product->sku = 'PROD-9999';
  8. $product->commerce_price->amount = 500; // Price in minors units 500 = $5
  9. $product->commerce_price->currency_code = 'USD'; // Use your currency... obviously :-)
  11. // You can assign other fields with the same construction: $wrapper->field_name = ...
  12. $product->save();
  14. // Create a Product Display
  15. // Specify the title (typically required before saving)
  16. // And set the product reference up
  17. $product_display = entity_metadata_wrapper('node',entity_create('node', array('type' => 'product_display','uid'=>$user->uid)));
  18. $product_display->title = 'Test Product Display';
  19. $product_display->field_product[] = $product;
  21. // Save the node.
  22. $product_display->save();


Rene's picture

THANK YOU! been reading many different discussions the last 2 days about creating products programmatically, and many of them was incomplete or had different approaches.

The only working after my intentions was this one!

Anonymous's picture

Thaks man , nicely put together this info.

Greatly appreciated!

Rodge's picture


Is it just me, or has anybody experiencing this error?

EntityMetadataWrapperException: Unknown data property field_product. in EntityStructureWrapper->getPropertyInfo()

I would like to accomplish a custum importer function for commerce. I need a custom importer, because the CSV structure is a whole lot different than a straight forward csv file.

Can anybody please help me out?

Hiraman's picture

Hi Rodge,

Just check product field name in your content type. 'field_product' is just for example. May be you have different field name in content type which you created to display the product.