[Drupal] How can we list contents of a particular vocabulary from the vocabularies lists

| | 2 min read

Consider that there is more than one vocabularies in your drupal website and we have to list them with the respective contents. Consider the situation where you have to list only the content of a particular vocabulary and not all the vocabularies. If you want to list the contents of a particular vocabulary then you can use the following code for doing that.

In the template.php file write the pre-process node function with the given code.


function themename_preprocess_node(&$vars) {
 global $base_url;
  // $vocabularies contains all the vocabularies added for the a particular content-type.
  $vocabularies = taxonomy_get_vocabularies($type = 'content-type');
  foreach($vocabularies as $key => $value) {
    if ($value->name == 'vocabulary_name') {
      $tags_vid = $value->vid;
    }
  }
  $terms = taxonomy_node_get_terms($vars['node']);
  $tags_terms = array();
  foreach ($terms as $term) {
    if ($term->vid == $tags_vid) {
      $tags_terms[$term->name] = $term;
    }
  }
  if (!empty($tags_terms)) {
    foreach ($tags_terms as $term) {
      // During preview the free tagging terms are in an array unlike the
      // other terms which are objects. So we have to check if a $term
      // is an object or not.
      if (is_object($term)) {
        $links[] = array(
          'title' => $term->name,
          'data' => '<a href="link to where the terms have to be redirected">' . $term->name . '</a>',
          'class' => 'taxonomy_term_' . $term->tid,
          'rel' => 'tag',
        );
      }
    }
  }
  // $vars['tag_terms'] will consist of an unordered list of required terms of the particular vocabulary 
  $vars['tag_terms'] = theme_item_list($links , 'Title' , 'ul' , array('class'=>'links inline'));

The above function will help you list the contents of a specific vocabulary terms.