Forums

Remove comma after last tag (3 posts)

  1. marieclairehill
    Member
    Posted 7 months ago #

    Hi, how do I remove the comma after the last tag? I've been searching the forums and internet in general and so far I've gathered that it has something to do with rtrim, however after much trial and error I don't know how to apply it specifically to my code (below):

    <div id="tags">
    <p><?php
    $posttags = get_the_tags();
    if ($posttags) {
      foreach($posttags as $tag) {
        echo $tag->name . ' ';
      }
    }
    ?></p>
    </div>

    Any assistance is much appreciated, thanks!

  2. alchymyth
    The Sweeper
    Posted 7 months ago #

    to state the obvious - there is no comma in your code.

    if you want to have a comma, you could try:

    <div id="tags">
    <p><?php
    $posttags = get_the_tags(); $sep = '';
    if ($posttags) {
      foreach($posttags as $tag) {
        echo $sep.$tag->name; $sep = ', ';
      }
    }
    ?></p>
    </div>
  3. marieclairehill
    Member
    Posted 7 months ago #

    Thanks so much! That worked perfectly. (just to note I pasted the code before I had inserted the comma and space, which was as below, but yours solved my comma-at-the-end issue:)

    <div id="tags">
    <p><?php
    $posttags = get_the_tags();
    if ($posttags) {
      foreach($posttags as $tag) {
        echo $tag->name . ', ';
      }
    }
    ?></p>
    </div>

Reply

You must log in to post.

About this Topic