Last active
August 29, 2015 13:58
-
-
Save kvnm/9962693 to your computer and use it in GitHub Desktop.
Get a custom list of all Drupal terms on an entity. Useful when you have several term reference fields on a single entity, and want to display them all together. _get_entity_terms() written by Drupal user HydroZ.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Example: get all terms attached to a given taxonomy term. | |
* | |
* Can be done with any entity. | |
*/ | |
function custom_example($term) { | |
$related_term_links = array(); | |
$related_tids = _get_entity_terms('taxonomy_term', $term->vocabulary_machine_name, $term); | |
$related_terms = taxonomy_term_load_multiple($related_tids); | |
foreach ($related_terms as $related_term) { | |
$related_term_links[] = l($related_term->name, 'taxonomy/term/' . $related_term->tid); | |
} | |
if (!empty($related_term_links)) { | |
$output = '<div class="related-terms"><span class="label">Related Topics:</span> ' . implode(' | ', $related_term_links) . '</div>'; | |
return $output; | |
} | |
} | |
/** | |
* Fetchs all Taxonomy Term IDs from Entity Object. All fields of field type "taxonomy_term_reference" will be included. | |
* | |
* @param String $entity_type | |
* @param $string $bundle | |
* @param Object $entity | |
* | |
* @return array | |
* Array with tids of entity | |
*/ | |
function _get_entity_terms($entity_type, $bundle, $entity) { | |
$tids = array(); | |
foreach (field_info_field_map() as $field_name => $field_info) { | |
if ($field_info['type'] <> "taxonomy_term_reference") { | |
continue; | |
} | |
if (array_key_exists($entity_type, $field_info['bundles'])) { | |
if (in_array($bundle, $field_info['bundles'][$entity_type])) { | |
if (isset($entity->{$field_name})) { | |
$values = field_get_items($entity_type, $entity, $field_name); | |
foreach ((array)$values as $tid) { | |
$tids[] = $tid['tid']; | |
} | |
} | |
} | |
} | |
} | |
return array_unique(array_filter($tids)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment