dragunoff

wpquestions.com, ID = 2781

Aug 4th, 2011
522
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.30 KB | None | 0 0
  1. <?php
  2.  
  3. // determine the topmost parent of a term
  4. function get_term_top_most_parent($term_id, $taxonomy){
  5.  
  6.     // start from the current term
  7.     $parent  = get_term_by( 'id', $term_id, $taxonomy);
  8.  
  9.     // climb up the hierarchy until we reach a term with parent = '0'
  10.     while ($parent->parent != '0'){
  11.  
  12.         $term_id = $parent->parent;
  13.        
  14.         $parent  = get_term_by( 'id', $term_id, $taxonomy);
  15.  
  16.     }
  17.  
  18.     return $parent;
  19.  
  20. }
  21.  
  22. // so once you have this function you can just loop over the results returned by wp_get_object_terms
  23. function hey_top_parents($taxonomy) {
  24.  
  25.     // get temrs for current post
  26.     $terms = wp_get_object_terms( get_the_ID(), $taxonomy );
  27.  
  28.     // set vars
  29.     $top_parent_terms = array();
  30.  
  31.     foreach ( $terms as $term ) {
  32.  
  33.         //get top level parent
  34.         $top_parent = get_term_top_most_parent( $term->term_id, $taxonomy );
  35.  
  36.         //check if you have it in your array to only add it once
  37.         if ( !in_array( $top_parent, $top_parent_terms ) ) {
  38.  
  39.             $top_parent_terms[] = $top_parent;
  40.  
  41.         }
  42.  
  43.     }
  44.  
  45.     // build output (the HTML is up to you)
  46.     $r = '<p>Parent terms:</p><ul>';
  47.    
  48.     foreach ( $top_parent_terms as $term ) {
  49.  
  50.         $r .= '<li><a href="' . get_term_link( $term->slug, $taxonomy ) . '">' . $term->name . '</a></li>';
  51.  
  52.     }
  53.    
  54.     $r .= '</ul>';
  55.    
  56.     // return the results
  57.     return $r;
  58.    
  59. }
Advertisement
Add Comment
Please, Sign In to add comment