编程为 Drupal 节点添加分类术语

hooface 提交于 周六, 2016-03-12 - 20:55

一、Drupal 6 的实现方式

//多个术语的标签(Tags)
$node->taxonomy = array('tags' => array( $vid => 'tag1, tag2'));

//如果是单个术语,可以按下面的方式
$node->taxonomy = array( $vid => $tid);

//保存
taxonomy_node_save($node, $node->taxonomy);
//或者
node_save($node);

已知词汇和术语,保存到节点的方式:

/**
 * Get taxonomy array to add to node object on presave in hook_nodeapi
 *
 * @param unknown_type $value
 * @param unknown_type $voc
 * @return unknown
 */
function linkchecker_get_term($value="New", $voc = "features_link_state"){
  
  $vid = db_result(db_query("SELECT vid FROM {vocabulary} WHERE module = '%s';", $voc));
  
  $term = db_fetch_array(db_query('SELECT tid FROM {term_data} WHERE name LIKE "%s" AND vid = %d', $value, $vid));
  
  return array($indication['vid'] => array($term['tid'] => $term['tid']));
}

...

$node->taxonomy = linkchecker_get_term();
Update Taxonomy term tags, remove existing from the vocabulary and set a new one. If it does not exist add it first and then set it to the node.
/**
 * Set a clean new taxonomy tag
 *
 * @param unknown_type $nid
 * @param unknown_type $voc
 * @param unknown_type $tag
 * @return unknown
 */
function _set_clean_term($nid, $voc, $tag){
    
        if (is_numeric($nid) AND is_numeric($voc) AND is_string($tag)) {
        
        if($result = db_query("SELECT tid FROM {term_data} WHERE vid = %d", $voc)) {
          while ($data = db_fetch_object($result)) {
            $terms[$data->tid] = $data->tid;
          }
        }
        
        $terms_tids = implode(", ", $terms);
        
        db_query('DELETE FROM {term_node} WHERE nid = %d AND tid IN (%s)', $nid, $terms_tids);
        
        
        $tid = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d", $tag, $voc));
        
        if (!$tid) {
            //Add new term
            $edit = array(
                'vid' => $voc,
                'name' => $tag,
            );
            
            taxonomy_save_term($edit);

            $tid = $edit['tid'];
        }

        db_query("INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)", $nid, $nid, $tid);
        
        return $tid;
    }
}

Drupal 7 实现方式

最基本的术语
taxonomy_term_save((object) array(
  'name' => 'Term name',
  'vid' => 'vocabulary id',
));
如果分类术语有一个自定义字段,必须使用下面的代码:
$term = new stdClass();
$term->name = ‘Your New Term Name’;
$term->vid = 'vocabulary id'; 
$term->field_new[LANGUAGE_NONE][0]['value'] = ‘Value for this field’; 
taxonomy_term_save($term);
参考: http://www.zimplicit.se/en/knowledge/save-taxonomy-terms-programmatical… http://www.lightrains.com/blog/programmatically-create-taxonomy-term-dr…