0

Been trying do this and still no luck. What I'm trying is to list taxonomy terms assigned to a post ordered by parent-child category relationship (hierarchical view).

Structure is something like this

Library = custom post type      
Year = custom taxonomy assigned to "library" 
    
- 2021 = parent term     
-- April = child term
-- May = child term
-- June = child term
-- July = child term

The desired output is:

2021, April, May, June, July

I tried:

$terms = get_the_terms( $post->ID, 'document_year' ); 
if ( $terms && ! is_wp_error( $terms ) ) : 
    $output = array(); 
    foreach ( $terms as $term ) {
        $output[] = $term->name;
    }
    echo '<span>' . implode ( ', ', $output ) . '</span>'; 
endif;

But this outputs an alphabetical order of terms.

Same with this:

echo ( get_the_term_list( $post->ID, 'category', '', ' / ') );

Any help please?

1 Answer 1

0

If you have a need to build up an actual structure of terms, this might be a useful method for you:

/**
 * Recursively sort an array of taxonomy terms hierarchically. Child categories will be
 * placed under a 'children' member of their parent term.
 * @param Array   $cats     taxonomy term objects to sort
 * @param Array   $into     result array to put them in
 * @param integer $parentId the current parent ID to put them in
 */
function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0)
{
    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parentId) {
            $into[$cat->term_id] = $cat;
            unset($cats[$i]);
        }
    }

    foreach ($into as $topCat) {
        $topCat->children = array();
        sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
    }
}

Usage is as follows:

$categories = get_terms('my_taxonomy_name', array('hide_empty' => false));
$categoryHierarchy = array();
sort_terms_hierarchically($categories, $categoryHierarchy);

var_dump($categoryHierarchy);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.