How to create Drupal Commerce products programmatically

Kristian Polso • August 20, 2014

Drupal 7 Commerce Drupal Planet

Sometimes you just need to get your hands dirty and start adding Drupal Commerce products programmatically. Luckily that is not that hard of an thing to do.

Create a Product entity:

       // Product       $product = commerce_product_new('product');       $product->sku = "PRODUCT-SKU";       $product->title = "Product Title";       $product->language = LANGUAGE_NONE;       $product->uid = 1;       $product->commerce_price[LANGUAGE_NONE][0] = array(         'amount' => 10 * 100, // $10         'currency_code' => "USD",       );       commerce_product_save($product);

 

To set the product category (which is a taxonomy term):

       $product->field_product_category[LANGUAGE_NONE][0]['tid'] = 1; // 1 = the term id

 

To set the stock:

       $product->commerce_stock[LANGUAGE_NONE][0]['value'] = 1;

 

To set VAT / Sales Tax:

       $product->commerce_price[LANGUAGE_NONE][0]['data']['include_tax'] = "vat"; // "vat" = machine name for the tax       $product->commerce_price[LANGUAGE_NONE][0]['include_tax'] = "vat"; // "vat" = machine name for the tax

 

If you modify any of these fields, remember to run "commerce_product_save($product);" at the end.

 

To create a Product display for your new product, you need to use the previously used $product variable.

       // Product display       $node = (object)array('type' => 'product_display');       node_object_prepare($node);       $node->title = "Product Display Title";       $node->uid = 1;       $node->field_product[LANGUAGE_NONE][]['product_id'] = $product->product_id;       $node->language = LANGUAGE_NONE;       node_save($node);

Share This Post