Home > front end >  Separate categories by ","
Separate categories by ","

Time:02-03

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 ><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>',',';
            $count  ;
        }
    }   
}

I would like it to stay Category1, Category2

Intente usando explode e implode.

CodePudding user response:

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 ><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>',',';
$count  ;

to

echo '<span ><a href="' . $term_link . '" rel="tag">' . $firstTerm->name . '</a></span>';

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

$count  ;

CodePudding user response:

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

  • Related