Showing posts with label field_attach_load. Show all posts
Showing posts with label field_attach_load. Show all posts

Sunday, 12 June 2011

Vocabulary by machine name, taxonomy_get_tree() and $user

(Amended on 17 Jul 2011 to replace reloading entire entities with using field_attach_load().)

Getting the ID of a vocabulary has long been a problem in Drupal but Drupal 7 goes a long way to resolving that:

$voc = taxonomy_vocabulary_machine_name_load('vocab_machine_name');

And you've got it.

However if you want to load a taxonomy_tree you still have to use the vocabulary ID so you run the line above first, and then:

$tree = taxonomy_get_tree($voc->vid, [parent], [depth], [internal value]);

The last two parameters on taxonomy_get_tree() have been swapped so if you want to specify the depth you don't have to do (..., -1, $depth) just (..., $depth). Which is handy.

Note that taxonomy_get_tree() does not return a full entity, which is unfortunate if you want any fields that have been attached to the terms. You have to fetch the fields separately but it's not hard:

$tree = taxonomy_get_tree($voc->vid);
foreach ($tree as $key => $term) {
  $terms[$key] = $term->tid;
}
field_attach_load('taxonomy_term', $terms);


The same applies to the global $user variable. This is normally the user without attached fields, so if you need a field that has been attached...


global $user;
field_attach_load('user', array($user->uid => $user));

Hope that helps.