Getting sorted hierarchy of categories
-
Hello!
I’m trying to retrieve the hierarchy of categories (default WP taxonomy) a post belongs to (normal blog post, not custom post type).
I’ve tried every function possible but the order in which they are retrieve, seems pretty much random.I have the following tree of categories:
– Perros (dogs)
— Razas (breeds)
—— Rottweiler
– Gatos (cats)
— Razas (breeds)
—— Esfinge / SphynxFor the post about Rottweiler I get the hierarchy with this order:
Perros (dogs) > Razas (breeds) > Rottweiler
(as defined in the dashboard).
For the post about the Esfinge / Sphynx I get the hierarchy with this order:
Esfinge / Sphynx > Gatos (cats) > Razas (breeds)So they are in completely different order. I’ve tried their retrieval with every function I’ve come up:
– get_the_category()
– wp_get_object_terms
– get_the_termsOnly a combination of ‘wp_list_categories’ and ‘wp_list_categories’ seems to do the trick.
$taxonomy = 'category'; // Get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // Separator between links. $separator = ', '; if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( array( 'title_li' => '', 'style' => 'none', 'echo' => false, 'taxonomy' => $taxonomy, 'include' => $term_ids ) ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // Display post categories. echo $terms; }
Is this expected? Why doesn’t it retrieve them in the defined hierarchical order (or any other consistent order) by default?
Thanks!
- The topic ‘Getting sorted hierarchy of categories’ is closed to new replies.