How to programmatically link commerce products to taxonomy terms I'm trying to link existing commerce products to an existing taxonomy term in Drupal 7:

$products = commerce_product_load_multiple($pids);
foreach($products as $product){
    $product-&gt;field_some_option[LANGUAGE_NONE][0]=$tid; //the taxonomy term id
    commerce_product_save($product);
}


This doesn't work.

Typically when I assign the taxonomy term to the product via the admin pages it adds an entry to a database table called field_data_field_some_option, which contains the product and term id. When I use the above code, a new entry is again made in the table, but the term id is set as NULL.

Note that I'm trying to link commerce products, not product displays, which as far as I understand means I can't use the typical node-taxonomy linking approach.

Anyone know how to get this working, short of bypassing Drupal APIs and editing the database directly?
You're close, but need to tweak setting the field value to:

$product-&gt;field_some_option[LANGUAGE_NONE][0]['tid'] = $tid;


For the taxonomy term reference field uses the 'tid' key there.

You could also do it with a metadata wrapper like: 

$wrapper = entity_metadata_wrapper('commerce_product', $product);
// Append to existing field value
$values = $wrapper-&gt;field_some_option-&gt;raw();
$values[] = $tid;
// Set field values
$wrapper-&gt;field_some_option-&gt;set($values);
$wrapper-&gt;save();