Information for: DEVELOPERS   PARTNERS

Attach terms to another entity programmatically

Lesson Goal

Attach existing terms to entities with a taxonomy term reference field.

Implementation Method

Drupal Version


Drupal 7

  1. Load the node or user object.
  2. Assign a term ID to the appropriate field.
  3. Save the node or user object.

Drupal 8


In Drupal 7 you can only attach term reference fields to Content Types and Users. In Drupal 8 you can attach term reference fields to any entity type.

Drupal 7 method

Place the following code in the lotus.module file:

function lotus_attach_term() {
$node = node_load($nid); // $nid is the node id of the node to update.

// field_example_term_reference: is the field name of a term reference
field attached to your content type.
// 4: is the term ID you want to assign to the node.
$node->field_example_term_reference[$node->language][]['tid'] = 4;
node_save($node); // Save the changes.

Drupal 8 method

Place the following code in the lotus.module file:

 use Drupal\node\Entity\Node;

 * Before attaching a term(s) to a term reference field,
 * Must know:
 * - field_example_name: the full name of the term reference field
 * - tid: the term ID(s) to attach
 * Keep in mind that this example uses Node::load()
 * but you can use any Entity::load()
 * e.g. User::load(), Term::load(), etc.

 // Example 1: attaching a single term
 $node = \Drupal\node\Entity\Node::load($nid);

 // Attach only one term
 $tid = 1; // The ID of the term to attach.
 $node->set('field_example_name', $tid);
 // End of Example 1 />

 // Example 2: attaching multiple terms
 $node2 = \Drupal\node\Entity\Node::load($nid2);

// To attach multiple terms, the term IDs must be in an array.
$multiple_tids = array(1, 2, 3); // Each is Term ID of an existing term.
$node2->set('field_example_name', $multiple_tids);
// Note that field_example_name must allow multiple terms.
// End of Example 2 />