get_the_term_list by hierarchy order

    function btp_entry_capture_categories() {
        $out="";

        global $post;

        $taxonomies = get_object_taxonomies( $post );

        foreach ( $taxonomies as $taxonomy ) {  
            $taxonomy = get_taxonomy( $taxonomy );  
            if ( $taxonomy->query_var && $taxonomy->hierarchical ) {

                $out .= '<div class="entry-categories">';
                    $out .= '<h6>' . $taxonomy->labels->name . '</h6>';
                    $out .= get_the_term_list( $post->ID, $taxonomy->name, '<ul><li>', '</li><li>', ' › </li></ul>' );
                $out .= '</div>';
            }
        }

        return $out;
    }

I’m trying to output the category list ordering by hierarchy, is it possible to do with my code? what would be the best approach to do that?

1 Answer
1

get_the_term_list() will not work here. The best function to use would be wp_get_post_terms()

With the following assumption, this can work

  • If a post only belongs to one parent, one child and/or one grandchild, you can order the terms by term_id.

  • It is widely accepted that the parent will have a lower numbered ID than the child and the child will have a lower numbered ID than the grandchild

With this info, you can get the post terms as follow then inside your code

wp_get_post_terms( $post->ID, $taxonomy->name, array( 'orderby' => 'term_id' ) );

But as I said, you will need to have your post have only one parent, one child and one grandchild in the same tree

EDIT

You can try something like this. You will just need to add the HTML mark-up yourself

function btp_entry_capture_categories() {
    $out="";

    global $post;

    $taxonomies = get_object_taxonomies( $post );

    foreach ( $taxonomies as $taxonomy ) {  
        $taxonomy = get_taxonomy( $taxonomy );  
        if ( $taxonomy->query_var && $taxonomy->hierarchical ) {

            $out .= '<div class="entry-categories">';
                $out .= '<h6>' . $taxonomy->labels->name . '</h6>';

                $terms = wp_get_post_terms( $post->ID, $taxonomy->name, array( 'orderby' => 'term_id' ) );
                foreach ( $terms as $term ) {

                    $out .= $term->name;

                }
            $out .= '</div>';
        }
    }

    return $out;
}

Leave a Comment