-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 :(

3
  • change ` return "<a href='$url'>$name</a>";` to echo "<a href='$url'>$name</a>"; Commented Oct 30, 2020 at 13:51
  • 1
    @angel.bonev That's not at all correct. See Wordpress using echo vs return in shortcode function Commented Oct 30, 2020 at 13:52
  • @esqew you did a great job with your answer Commented Oct 30, 2020 at 14:01

1 Answer 1

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick reply, which solved my problem ;) I think I understand why your solution works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.