get_terms problem : related articles

I’m trying to use get_the_term_list to catch the name of the current taxonomy of the page, and then use it with get_terms and a foreach method, to show the result of all the “elements” from the same taxonomy, but i only got an empty result. (for example, this is to have the related articles of the page).

Do you know why it doesn’t work? The echo on get_the_term_list works ok, but then in the parameter of get_terms, the result of the “li”s is blank.

Read More
$my_tax = get_the_term_list( $post->ID, 'type');
//echo $my_tax;?> output works fine

$terms = get_terms($my_tax);
foreach ($terms as $term) {
echo "<li>".$term->name."</li>"; // empty
}

Could you help me?

Related posts

Leave a Reply

2 comments

  1. get_the_term_list() is retrieving the terms attached to the post that are in the taxonomy “types”.

    get_terms() is designed to retrieve all the terms within a taxonomy.

    What you are trying to do is use get_terms() for a specific term in a taxonomy, not a taxonomy itself.

    You need to do: $terms = get_terms('type');

  2. get_post_taxonomies( $post->ID ) allows you to dynamically retrieve the names of the taxonomies attached to a post.

    So you could retrieve ALL of the terms that belong to the current post’s taxonomies:

    $all_terms = get_terms( get_post_taxonomies( $post->ID ) );
    

    OR just the terms that are assigned to the current post:

    $object_terms = wp_get_object_terms( $post->ID, get_post_taxonomies( $post->ID ) );
    

    I’ll take it a step further and implement get_the_term_list() for each taxonomy:

    foreach( get_post_taxonomies( $post->ID ) as $taxonomy ) {
        $taxonomy_name = get_taxonomy( $taxonomy )->labels->name;
        echo get_the_term_list( $post->ID, $taxonomy, '<h3>' . $taxonomy_name . '</h3><ul><li>', '</li><li>', '</li></ul>' );
    }