Search code examples
wordpressdatatabletaxonomy-terms

WordPress: the_terms() is not rendering my taxonomy links as expected, why?


I use a datatable in my WordPress plugin to display titles and taxonomies but I am not get it to work properly in the output.

This line:

$return .="<td>" . the_terms( $post->ID , 'authors', '', ', ' ) . "</td>";

Result:

<a href="www.example.com/author1/" rel="tag">Author 1</a>
<a href="www.example.com/author2/" rel="tag">Author 2</a>

and leaves the <td></td><td></td> empty.

I want this result:

<td>
    <a href="www.example.com/author1/" rel="tag">Author 1</a>
</td>
<td>
    <a href="www.example.com/author2/" rel="tag">Author 2</a>
</td>

Multiple authors should be seperated by: ,

Any solutions?


Solution

  • The the_terms() function echoes the value right away which is why your post tags are being rendered outside of your td tags.

    From the documentation:

    Displays the terms for a post in a list.

    When you want to assign the returned value to a variable you want to use get_the_terms() instead, like so for example (untested but should get you on the right track):

    $term_obj_list = get_the_terms( $post->ID, 'authors' );
    $term_links = array();
    
    if ( $term_obj_list && ! is_wp_error( $term_obj_list ) ) :
    
        foreach( $term_obj_list as $term ):
            $term_links[] = '<a href="' . esc_attr( get_term_link( $term->slug, 'authors' ) ) . '">' . $term->name . '</a>';
        endforeach;
    
        $return .= "<td>" . join( ', ', $term_links ) . "</td>";
    
    endif;