Advertisement
luisabarca

Show custom taxonomies hierarchical

Oct 10th, 2013
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. function custom_taxonomies_terms_links()
  2. {
  3.     // get post by post id
  4.     $post = get_post( $post->ID );
  5.  
  6.     // get post type by post
  7.     $post_type = $post->post_type;
  8.  
  9.     // get post type taxonomies
  10.     $taxonomies = get_object_taxonomies( $post_type, 'objects' );
  11.     $out = '';
  12.    
  13.     $format_start_list = "<h2>%s</h2><ul>\n";
  14.     $format_start_parent = "<li><h3>%s</h3><ul>\n";
  15.     $format_item = "<li><a href=\"%s\">%s</a></li>\n";
  16.     $format_end_parent = "</ul></li>\n";
  17.     $format_end_list = "</ul>\n";
  18.    
  19.     foreach ( $taxonomies as $taxonomy_slug => $taxonomy ) {
  20.         $ordered_terms = array();
  21.        
  22.         // get the terms related to post
  23.         $terms = get_the_terms( $post->ID, $taxonomy_slug );
  24.  
  25.         if ( !empty( $terms ) ) {
  26.             $out .= sprintf($format_start_list, $taxonomy->label);
  27.  
  28.             foreach ( $terms as $term ) {
  29.                 if ( $term->parent < 1 ) {
  30.                     $ordered_terms[$term->term_id]['parent'] = $term;
  31.                 } else {
  32.                     $ordered_terms[$term->parent]['items'][$term->term_id] = $term;                    
  33.                 }
  34.             }
  35.            
  36.             foreach ($ordered_terms as $id => $terms) {                
  37.                 $out .= sprintf($format_start_parent, $terms['parent']->name);
  38.            
  39.                 foreach ($terms['items'] as $term) {
  40.                     $out .= sprintf($format_item, get_term_link($term->slug, $taxonomy_slug), $term->name);
  41.                 }
  42.                
  43.                 $out .= $format_end_parent;
  44.             }
  45.            
  46.  
  47.             $out .= $format_end_list;
  48.         }
  49.     }
  50.  
  51.     return $out;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement