1

I am building a website with Drupal 7, this website contains a blog. For some reasons I use a custom content type for blog posts call bog_post. In this content type I add a "Term reference" field (is machine name is "field_blog_categories").

To custom the layout of blog post I override node--blog_post.tpl.php. My problem is to display the term reference field. When I print the php var corresponding to that field "$field_blog_categories" I get :

Array ( [en] => Array ( [0] => Array ( [tid] => 8 ) ) )

As you can see the term name don't appear. I thought to get the name by tid. I try

taxonomy_term_load($field_blog_categories['en'][0]['tid'])

but it return nothing.

Any help to get the term name will be appreciate !

  • I make a mistake, actually taxonomy_term_load($field_blog_categories['en'][0]['tid']) works but I don't print the result... taxonomy_term_load() return an array which include the name. However thanks for your answer ! – a.b.d Jun 16 '11 at 8:29
1

If taxonomy_term_load() return false then

  • the supplied argument (tid) is either non-numeric
  • Or there is no term with this id.

To check if there is any term against this id try

`taxonomy_term_load_multiple(array($tid), array());`

If taxonomy_term_load_multiple() returns empty array then it is clear there is no term with this $tid.

1

As an alternate approach, you could try using the function

<?php
/**
 * Get a list of all taxonomy terms
 */
function taxonomy_node_get_terms($node, $key = 'tid') {
    if(arg(0)=='node' && is_numeric(arg(1))) {  
        static $terms;
        if (!isset($terms[$node->vid][$key])) {
            $query = db_select('taxonomy_index', 'r');
            $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
            $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
            $query->fields( $t_alias );
            $query->condition("r.nid", $node->nid);
            $result = $query->execute();
            $terms[$node->vid][$key] = array();
            foreach ($result as $term) {
                $terms[$node->vid][$key][$term->$key] = $term;
            }
        }
        return $terms[$node->vid][$key];
    }
}

/* just guessing at this function - it might need tweaking! */

function theme_preprocess_page(&$variables) {
    $node = node_load(arg(1));
    $results = taxonomy_node_get_terms($node);
    if(is_array($results)) {
        foreach ($results as $item) {
           $variables['your_taxonomy_terms'][] = $item->name; 
        }
    }
}
?>

Then you could call $your_taxonomy_terms from your page template and it should return the names.

This is all based on the thread here -> http://drupal.org/node/1072806

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.