skip to Main Content

When separating the categories, the "," appears in the last category. e.g
Category1, Category2,

I am using this function.

// MultiNetwork
function MultiNetwork() {
    global $post;
    $terms = get_the_terms( $post->ID, 'networks');
    $count = 0;
    foreach ( $terms as $term ){
        if ($count <= 1) {  
            $firstTerm = $term;
            $term_link = get_category_link($firstTerm->term_id);    
            echo '<span class="network"><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>',',';
            $count++;
        }
    }   
}

I would like it to stay
Category1, Category2

Intente usando explode e implode.

2

Answers


  1. For your case, simply only echo the "," if that is not the last item.

    For example, remove ,',' and then add the following line:

    if ($count < count($terms)) { echo "," ;}
    

    So Change these two lines:

    echo '<span class="network"><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>',',';
    $count++;
    

    to

    echo '<span class="network"><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>';
    $count++;
    
    if ($count < count($terms)) { echo "," ;}
    
    
    Login or Signup to reply.
  2. You can you use below code to resolve ", " problem.

     $terms = get_terms([
      'taxonomy' => 'networks',
      'hide_empty' => false,
    ]);
    
    $count = 0;
    foreach ( $terms as $term ){
      if ($count <= 1) {  
         $cat[] = $term->name;
         $count++; 
      }
    }   
    
    $data = implode(', ', $cat);
    

    I have tried this code for the same. please look for the screenshot I’m attaching below.

    Screen shot of result

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search