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();

}
Tags :

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon