Programmatically remove a taxonomy term tagged on all nodes

The following codes will remove a taxonomy term tagged on all nodes. Where $field_name is the machine name of the taxonomy term field and the $tid is the taxonomy term ID.

  
$field_name = 'tags';
$tid = '2';

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'term_item')
  ->fieldCondition($field_name, 'tid', $tid);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes[$tid][$field_name] = entity_load('node', $nids, array(), TRUE);
  foreach ($nodes as $node) {
    $field = &$node->{$field_name}[$node->language];
    foreach ($field as $index => $term) {
      if ($term['tid'] == $tid) {
        unset($field[$index]);
        node_save($node);
      }
    }
  }
}
  

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.