-1

I am trying to print all terms associated with a specific WordPress post. I have found good starting points (my approach is based on this article: https://theeventscalendar.com/knowledgebase/k/add-a-list-of-category-links-below-the-search-bar/), however, I fail at getting the result I want, which would be a single line of terms with links, seperated by commas.

e.g.:


<a href="link to term 1">Term 1</a>, <a href="link to term 2">Term 1</a>

What I currently have is:

add_shortcode( 'tribe_links_ineko', 'tribe_get_links_ineko' );

function tribe_get_links_ineko () {
  $terms = get_terms( [
    'taxonomy' => Tribe__Events__Main::TAXONOMY
  ] );
 
  if ( empty( $terms ) || is_wp_error( $terms ) ) {
    return;
  }
  
    echo '<div><p>';
  foreach ( $terms as $single_term ) {
    $url = esc_url( get_term_link( $single_term ) );
    $name = esc_html( get_term_field( 'name', $single_term ) );
 
    return "<a href='$url'>$name</a>";
  }
 echo'</p><div>';
};

However, this only returns one of the terms. If I use echo instead of return, it returns all of the terms, but they get printed to the top of the page (using shortcode to place the output). As far as I understand it this is expected behavior for return, however, I cannot find an explanaition as to why echo is printed in the wrong place and on how to fix this.

Maybe someone could point me in the right direction, as I have no idea of php :(

Kim S.
  • 11
  • 4

1 Answers1

0

Build the string by concatenating into a single variable before returning, as opposed to returning straight away:

add_shortcode( 'tribe_links_ineko', 'tribe_get_links_ineko' );

function tribe_get_links_ineko () {
  $terms = get_terms( [
    'taxonomy' => Tribe__Events__Main::TAXONOMY
  ] );
 
  if ( empty( $terms ) || is_wp_error( $terms ) ) {
    return;
  }
  
  $out = '<div><p>';
  foreach ( $terms as $single_term ) {
    $url = esc_url( get_term_link( $single_term ) );
    $name = esc_html( get_term_field( 'name', $single_term ) );
 
    $out = $out . "<a href='$url'>$name</a>";
  }
 $out = $out . '</p><div>';
 return $out;
};
esqew
  • 42,425
  • 27
  • 92
  • 132
  • Thank you for the quick reply, which solved my problem ;) I think I understand why your solution works. – Kim S. Oct 30 '20 at 14:03