0

I have term with tid=9 (sublevel 3). It is nested under 2 other terms. I use following code to get names of its parent terms:

    <?php
//term id of term that you are checking for top parent
$term_tid = '9';
//this will be your top parent term if any was found
$top_parent_terms = array();

$parent_terms = taxonomy_get_parents_all($term_tid);

//top parent term has no parents so find it out by checking if it has parents
foreach($parent_terms as $parent) {
  $parent_parents = taxonomy_get_parents_all($parent->tid);
  if ($parent_parents != false) {
    //this is top parent term
    $top_parent_term[] = $parent;
  }
return $top_parent_term;
}
?>

Problem: As a result I am getting "array" with error: "Notice: Array to string conversion in php_eval() " instead of terms names. I tried bunch of other solutions but none of them work or I get same error (for example here https://api.drupal.org/comment/59421#comment-59421)

0

I think this is closer to what you want:

<?php
    //term id of term that you are checking for top parent
    $term_tid = '9';
    $parent_terms = taxonomy_get_parents_all($term_tid);

    //top parent term has no parents so find it out by checking if it has parents
    foreach ($parent_terms as $parent) {
      $parent_parents = taxonomy_get_parents_all($parent->tid);
      if (empty($parent_parents)) {
        //this is top parent term
        return $parent;
      }
    }
?>

Explanation:

  • You don't need the $top_parent_terms variable. You can return the first $parent you encounter that doesn't have a $parent_parent.
  • You were also probably having issues because you declare $top_parent_terms, but reference $top_parent_term (missing an 's').
  • Also, this bit $top_parent_term[] = $parent would produce a result like this: $top_parent_term = array(0 => $parent) when you probably want $top_parent_term = $parent.
  • Note that the returned $parent variable will be an object, not an array. taxonomy_get_parents_all returns an array of term objects.
| improve this answer | |
  • Thank you. i tried your code - the error is gone however the result is always empty. The result should show 2 taxonomy terms above this term. – loparr Dec 16 '16 at 20:10
  • OK, I'll try it on my site and see if I can work it out. – Labracadabrador Dec 19 '16 at 17:01

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.