(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.
6 comments:
thanks you for this post, it works perfectly for me !
Great! Glad it helped. (One day I'll figure out how to use field_attach_load() to do the same job only quicker.)
Aha, discovered where I was going wrong with field_attach_load - the array of entities must be indexed by the entity id.
So to load the fields for a user:
field_attach_load('user', array($user->uid => $user));
I have amended the blog itself.
suscribin buddy
As you can see on the Drupal API site the full signature is
taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE)
So instead of calling field_attach_load('taxonomy_term', $terms) you could get away with
taxonomy_get_tree($vid, 0, NULL, TRUE)
and automatically load the full term entities.
Well knock me down with a feather - that's right.
(But the $user object is still incomplete unless you specifically load it.)
Post a Comment