functions – Get Comma Seperated Taxonomy Linked Terms and Last Child Separated By “&” Instead Of Comma

Question

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.

0
Joe Titus 4 months 2022-04-12T15:50:15-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse