Get the parent term in a taxonomy with a hierarchy (tree) in Drupal 7

Lotaxonomy_get_parents() returns all the parent terms for the taxonomy term with the ID passed as argument.
The value returned from the function is an array having the following structure:

array( 'term id' =>
 [taxonomy term object] )

The taxonomy term object contains a property for each of the fields contained in the “term_data” table.

The code used from the function is essentially the following one.

$result = db_query(
db_rewrite_sql(
'SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} 
h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), 
$tid); $parents = array(); while ($parent = db_fetch_object($result)) 
{
 $parents[$parent->$key] = $parent; 
}

As you see, it doesn’t return the parent terms of the parent terms of the one passed as argument. For that you need taxonomy_get_parents_all(), which executes the following code.
if ($tid) { $parents[] = taxonomy_get_term($tid); $n = 0; while ($parent = taxonomy_get_parents($parents[$n]->tid)) { $parents = array_merge($parents, $parent); $n++; } }
The function returns all the parent terms in the hierarchy. Ki

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

WordPress.com.

Up ↑

%d bloggers like this: