What you’re asking is a generic PHP/programming question, and this: “It links all terms to the last term link only“, is because your code clearly is attaching the link (i.e. the last value assigned to $term_link
) to the entire list ($entry_terms
), i.e. echo '<a href="' . esc_url( $term_link ) . '">' . $entry_terms . '</a>'
.
So what you should have done is, attach the link to the term name on this line: $entry_terms .= $term->name . $end;
, like so:
-
Replace this part:
$entry_terms .= $term->name . $end; $term_link = get_term_link( $term );
with this:
$term_link = get_term_link( $term ); $entry_terms .= '<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>' . $end;
And then, after that:
-
Replace the
$entry_terms = rtrim( $entry_terms, ', ' );
withecho rtrim( $entry_terms, ', ' );
. -
Remove the
echo '<a href="' . esc_url( $term_link ) . '">' . $entry_terms . '</a>';
.
Additional Notes
-
You should define
$entry_terms
before theforeach
line, i.e. add$entry_terms="";
. -
The ampersand sign is being displayed to the user, hence you need to escape the character, i.e. use
' & '
instead on line 4 in your original code.