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
Category:

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.

<?php

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);
  $node->save();
  
  // 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);
  $node->save();

}

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts

Search

Page Facebook