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