n Attach taxonomy terms to entity programmatically in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

in this tuto, I'll show you how to attach taxonomy terms to entity programmatically in Drupal 8.

Add the following code inside a function where you want to the attach taxonomy terms.


use Drupal\node\Entity\Node;

 * @param $variables
function mymodule_preprocess_page(&$variables)
  $node = Node::load('1');
  //Attach only one term
  $tid = 3; // The ID of the term to attach.
  $node->set('field_categories', $tid);
  // Attach multiple terms
  $multiple_tids = array(5, 6, 7); // the term IDs must be in an array. Each is Term ID of an existing term.
  $node->set('field_tags', $multiple_tids);


Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook