taxonomy_node_get_terms in Drupal

Like what I've said in my previous post, I've been experimenting with the CMS Drupal. And there was this time that I got tired of adding a very simple HTML code in every node that I insert in Drupal. So, I was thinking instead of putting the code in each of them, why not create some sort of block that works like it.

The function of the block is to display a text that links back to the taxonomy terms the node belongs to. At first, I was thinking of using PHP functions to do that i.e., retrieve the term ids the node belongs to, create a link using HTML code, etc. But then, there was an easier way to do it using just two functions:

The documentation from the official site of Drupal would clearly explain how these methods work. Anyways, I have used the l function to create the links and taxonomy_node_get_terms to get the terms the node belongs to without minding the vocabulary. Now all I have to do is create some simple PHP functions to make my block work. Here's my code:

<?php
if (arg(0) == 'node' && arg(1)) {
$categories = taxonomy_node_get_terms(arg(1));
foreach ($categories as $category) {
print l('Back to ' . $category->name,
'taxonomy/term/' . $category->tid,
array('title' => $category->name)) . '<br //>';
}
}
?>

Code is quite self explanatory I guess. arg(0) checks if the first argument in the URL is a node. arg(1) checks if the second argument (w/c is the node id) in the URL is set. So, therefore the first statement checks if the page is a node and if a node id is set. I've used taxonomy_node_get_terms(arg(1)) to get the node id of the current node and then stored the array to $categories. After that, I do a foreach statement to get the terms. You'll be able to view the values in the array by var_dump'ing $categories. I only need to retrieve the term id and category name. In other words, I only need $category->tid and $category->name. The statement 'taxonomy/term/' . $category->tid gets the URL of the term. print l was used to create the link.

1 comments:

  generic cialis

November 24, 2010 at 12:59 PM

In principle, a good happen, support the views of the author