get vocabulary id by name
There is no built in function for this, afaik. You can roll your own by calling taxonomy_get_vocabularies()
and search for your name in the resulting array, but this will do a database request on every call.
If you have a vocabulary that you often use from code, it might be easier/more effective to store the vid in a Drupal variable via variable_set()
once and get it back via variable_get()
(Many modules that create a vocabulary on install do it this way).
Edit: here is some sample code to do this on module install.
function mymodule_install() {
$ret = array();
$vocabulary = array(
'name' => t('myvocab'),
'multiple' => '1',
'required' => '0',
'hierarchy' => '1',
'relations' => '0',
'module' => 'mymodule',
'nodes' => array('article' => 1),
);
taxonomy_save_vocabulary($vocabulary);
$vid = $vocabulary['vid'];
variable_set('mymodule_myvocab', $vid);
return $ret
}
For Drupal 7 if you know the vocabulary machine name this is the way:
$vid = taxonomy_vocabulary_machine_name_load('your_vocabulary_name')->vid;
If you know only the Real name of vocabulary, you can use this function:
function _get_vocabulary_by_name($vocabulary_name) {
// Get vocabulary by vocabulary name.
$query = db_select('taxonomy_vocabulary', 'tv');
$query->fields('tv', [
'machine_name',
'vid',
]);
$query->condition('tv.name', $vocabulary_name, '=');
$vocabulary = $query->execute()->fetchObject();
return $vocabulary;
}
I have a function for this, well almost..
/**
* This function will return a vocabulary object which matches the
* given name. Will return null if no such vocabulary exists.
*
* @param String $vocabulary_name
* This is the name of the section which is required
* @return Object
* This is the vocabulary object with the name
* or null if no such vocabulary exists
*/
function mymodule_get_vocabulary_by_name($vocabulary_name) {
$vocabs = taxonomy_get_vocabularies(NULL);
foreach ($vocabs as $vocab_object) {
if ($vocab_object->name == $vocabulary_name) {
return $vocab_object;
}
}
return NULL;
}
If you want the vid just get the vid property of the returned object and.
$vocab_object = mymodule_get_vocabulary_by_name("listing");
$my_vid = $vocab_object->vid;
Henriks point about storing it in a variable is very valid as the above code you won't want to be running on every request.
Edit
Also worth noting that in Drupal 7 you can use taxonomy_vocabulary_get_names() which makes this a little easier.