0

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->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?

0

You're close, but need to tweak setting the field value to:

$product->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->field_some_option->raw();
$values[] = $tid;
// Set field values
$wrapper->field_some_option->set($values);
$wrapper->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.