0

I Want to List Custom Taxonomy Terms with Link and Separate Each with Comma but add "&" before the last term.

Example:

Drake, Migos, Ciara & Nicki

I found this answer that shows how to add '&' before the last term. BUT the terms are not linked which is what I am trying to achieve.

MY CURRENT CODE:

 $terms = get_the_terms( $post->ID, 'artist' );
            foreach($terms as $index => $term) {
                $enIndex = sizeof($terms) - 2;
    $end = (isset($terms[$enIndex]) && $index == $enIndex ? ' & ' : ', ');
    $entry_terms .= $term->name . $end;
    $term_link = get_term_link( $term );               
            }
            $entry_terms = rtrim( $entry_terms, ', ' );
                                       
 echo '<a href="' . esc_url( $term_link ) . '">' . $entry_terms . '</a>';           

CURRENT RESULT OF MY CODE:

Drake, Migos, Ciara & Nicki

My code is not working fine. It links all terms to the last term link only. Please help check my code. I am new WordPress development. Thanks.

1 Answer 1

1

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:

  1. 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:

  1. Replace the $entry_terms = rtrim( $entry_terms, ', ' ); with echo rtrim( $entry_terms, ', ' );.

  2. Remove the echo '<a href="' . esc_url( $term_link ) . '">' . $entry_terms . '</a>';.

Additional Notes

  1. You should define $entry_terms before the foreach line, i.e. add $entry_terms = '';.

  2. The ampersand sign is being displayed to the user, hence you need to escape the character, i.e. use ' &amp; ' instead on line 4 in your original code.

1
  • 1
    I have adjusted my code accordingly and it works flawlessly. thanks pal.
    – Joe Titus
    Apr 13 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.