Custom taxonomies

I have created a custom taxonomy ‘regionen’.

I have two levels inside the taxonomy

Anden
– Peru
– Bolivian
Conosur
– Chile
– Argentinien

I’m calling the taxonomy on the home page like this (‘see below’) and it lists all the terms for each post. Example Anden, Peru.

<?php the_terms( get_the_id(), 'regionen' ); ?>

What I would like to do is just call the relevant top level term ‘Anden or Conosur’ for each post on my index page and the second level term only on my single post pages??

Hopefully that makes sense and someone help explain this to me. Thanks for taking the time to read my problem.

1 Answer
1

You can use get_the_terms( int|WP_Post $post, string $taxonomy ) . See Codex detail here.

$my_terms = get_the_terms( get_the_id(), 'regionen' );
if ( ! empty( $my_terms ) ) {
    if ( ! is_wp_error( $my_terms ) ) {
        echo '<ul>';
            foreach( $my_terms as $term ) {
                if($term->parent == 0){
                    echo '<li><a href="' . get_term_link( $term->slug, 'regionen' ) . '">' . esc_html( $term->name ) . '</a></li>'; 
                }
            }
        echo '</ul>';
    }
}

Leave a Comment