skip to Main Content

I already tried some things with trim and so on but nothing works.

Maybe I made a mistake and you can help me? The code looks currently like that:

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
    $output = '';
    foreach ($terms as $term) {
      $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a>, ';
    }
};
echo $output;

2

Answers


  1. Try putting in substr_replace($term->name,"",-1), check documentation for more info, this should delete comma from last string.

    Login or Signup to reply.
  2. just add a counter to check the last item of the array

    $post = get_post();
    $terms = wp_get_post_terms($post->ID, 'genre');
    if ($terms)
    {
        $output = '';
        $i = 0;
        foreach ($terms as $term) {
          $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a> ';
    
          $output .= ($i == count($terms) - 1) ? '' : ',';
          $i++;
        }
    };
    echo $output;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search