Home › Forums › General Issues › Display Taxonomy Hierarchy › Reply To: Display Taxonomy Hierarchy
Sure, here’s a direct idea that you can use to display the taxonomy hierarchy on your WordPress website:
You can use the get_ancestors() function in WordPress to retrieve the ancestors of a taxonomy term. This function returns an array of term IDs, which you can then use to display the hierarchy.
Here’s an example code snippet that you can use:
<?php
// Get the current taxonomy term
$term = get_queried_object();
// Get the ancestors of the current term
$ancestors = get_ancestors( $term->term_id, $term->taxonomy );
// If there are ancestors, display them
if ( $ancestors ) {
// Reverse the order of ancestors to display them from parent to child
$ancestors = array_reverse( $ancestors );
// Loop through the ancestors and display them
for each ( $ancestors as $ancestor ) {
$ancestor_term = get_term( $ancestor, $term->taxonomy );
echo esc_html( $ancestor_term->name ) . ‘ – ‘;
}
}
// Display the current term
echo esc_html( $term->name );
?>
This code will retrieve the ancestors of the current taxonomy term and display them with the current term, separated by a dash. You can modify the output as per your requirements.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.