php - Remove last comma when listing tags wordpress

867

I have the following script to list a post's tags without links, but it puts a comma after all of the tags including the last one. Is there any way to prevent the script from adding a comma to the last tag in the list? I tried researching it, but there really isn't a whole lot out there about this particular wp string.

<?php
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo $tag->name . ', '; 
        }
    }
?> 
539

Answer

Solution:

Use rtrim. It will trim the last specified character.

    $posttags = get_the_tags();
    if ($posttags) {
       $taglist = "";
       foreach($posttags as $tag) {
           $taglist .=  $tag->name . ', '; 
       }
      echo rtrim($taglist, ", ");
   }
764

Answer

Solution:

if ($posttags) {
    echo implode(
        ', ', 
        array_map(
            function($tag) { return $tag->name; },
            $posttags
        )
    );
}
852

Answer

Solution:

I tend to do this when I need to concat a variable number of elements.

$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        $temp[] = $tag->name; 
    }
}
if (!empty($temp)) echo implode(', ',$temp);
398

Answer

Solution:

Change the placement of that Comma and put a small condition

<?php
    $posttags = get_the_tags();
    if ($posttags)
    {
        $first=true;
        foreach($posttags as $tag) 
        {
            if($first)
            {
                echo $tag->name; 
                $first=false;
            }
            else
            {
                echo ', '.$tag->name; 
            }
        }
    }
?> 
499

Answer

Solution:

You need the wordpress function . It will echo a tags so you won't need the whole loop.

People are also looking for solutions to the problem: PHP Curl with JSON data

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.