欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

drupal d6 d7 drupal6 drupal7 根据 节点 或者分类得到词汇表 有大用 有大大用

shiping1 的头像

I am going to check whether a term belongs to a designated vocabulary.

Which function is used to get vocabulary by term or node?

shareimprove this question
 add comment

up vote 11 down vote accepted

In Drupal 6, if you know the taxonomy term ID, you can get the vocabulary ID by using the following code:

$term = taxonomy_get_term($tid);
$vid = $term->vid;

If you have a node ID, then you can use the following code to get the vocabulary ID of all the taxonomy terms associated with the node using the following code:

$node = node_load($nid);
$vids = array();

if (!empty($node->taxonomy) {
  foreach ($node->taxonomy as $tid => $term) {
    $vids[] = $term->vid;
  }
}

In Drupal 7, the code would be the following:

$term = taxonomy_term_load($tid);
$vid = $term->vid;

In Drupal 7, the node property $node->taxonomy doesn't exist anymore. Instead, there is $node->field_<vocabulary_name>, which is an array with two different structures.

  • tags

    screenshot

  • other taxonomy terms

    screenshot

Using field_get_items(), you would get the taxonomy terms in the language they would be displayed, or in the language whose code is passed as argument to the function.

$items = field_get_items('node', $node, $field_name);

$node contains the node object, and $field_name the name of the taxonomy term field.

$items contains a simplified array, compared to the array contained in $node->field_<vocabulary_name>.

screenshot

shareimprove this answer
 add comment

Solved by the code below:

$tid = 18;    
$result = db_query("SELECT vid FROM {term_data} WHERE tid = %d", $tid);
$vid = db_result($result);
echo $vid;
shareimprove this answer
 add comment

For Drupal 7 the above code should be like this:

 $tid = 18;
 $vid = db_query('SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid', 
                  array(':tid' => $tid)
                )->fetchField();
 echo $vid;

See more examples at db_query() drupal 7 function.



来自 http://drupal.stackexchange.com/questions/6456/get-the-vocabulary-id-by-term-or-node

普通分类: