Same name and namespace in other branches
  1. 4.6.x modules/taxonomy.module \taxonomy_node_save()
  2. 4.7.x modules/taxonomy.module \taxonomy_node_save()
  3. 5.x modules/taxonomy/taxonomy.module \taxonomy_node_save()

Save term associations for a given node.

File

modules/taxonomy/taxonomy.module, line 671
Enables the organization of content into categories.

Code

function taxonomy_node_save(&$node, $terms) {
  taxonomy_node_delete_revision($node);

  // Free tagging vocabularies do not send their tids in the form,
  // so we'll detect them here and process them independently.
  if (isset($terms['tags'])) {
    $typed_input = $terms['tags'];
    unset($terms['tags']);
    foreach ($typed_input as $vid => $vid_value) {
      $typed_terms = drupal_explode_tags($vid_value);
      $inserted = array();
      foreach ($typed_terms as $typed_term) {

        // See if the term exists in the chosen vocabulary
        // and return the tid; otherwise, add a new record.
        $possibilities = taxonomy_get_term_by_name($typed_term);
        $typed_term_tid = NULL;

        // tid match, if any.
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }
        if (!$typed_term_tid) {
          $edit = array(
            'vid' => $vid,
            'name' => $typed_term,
          );
          $status = taxonomy_save_term($edit);
          $typed_term_tid = $edit['tid'];
        }

        // Defend against duplicate, differently cased tags
        if (!isset($inserted[$typed_term_tid])) {
          db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $typed_term_tid);
          $inserted[$typed_term_tid] = TRUE;
        }
      }
    }
  }
  if (is_array($terms)) {
    foreach ($terms as $term) {
      if (is_array($term)) {
        foreach ($term as $tid) {
          if ($tid) {
            db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $tid);
          }
        }
      }
      else {
        if (is_object($term)) {
          db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term->tid);
        }
        else {
          if ($term) {
            db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term);
          }
        }
      }
    }
  }

  // Flush the term "cache" for this node
  $node->taxonomy = taxonomy_node_get_terms($node, 'tid', TRUE);
}