skip to Main Content

I’m trying to call a list of tags in my wordpress single posts template and give each tag both a common and a unique css class.

I can successfully add a unique class "post-tags-(tag name here)" with following code:

<?php
$post_tags = get_the_tags();

if ( $post_tags ) {
    foreach($post_tags as $tag) {
        echo "<span class=post-tags-$tag->name>$tag->name</span>";
    }
}
?>

However I would need to add another common class called "post-tags" and I can’t find a way to add space between the tags.

<?php
$post_tags = get_the_tags();

if ( $post_tags ) {
    foreach($post_tags as $tag) {
        echo "<span class=post-tags&nbsp;post-tags-$tag->name>$tag->name</span>";
    }
}
?>

The &nbsp; I have added breaks the code. It simply returns

<span class="post-tags&nbsp;post-tags-tag3">tag3</span>

2

Answers


  1. Chosen as BEST ANSWER

    I got this answer from a friend and it fixed the problem

    echo "<span class="post-tags post-tags-$tag->name">$tag->name</span>";
    

    Basically you need to escape the apostrophes


  2. Try this

    $post_tags = get_the_tags();
    
    if ( $post_tags ) {
        foreach($post_tags as $tag) { ?>
    
    <span class="post-tags post-tags-<?php echo $tag->name; ?>"><?php echo $tag->name; ?></span>
    
    <?php
      }
    }
    ?>
    

    And if we use a tag for some css class, it’s better to use $tag->slug; or $tag->term_id; rather than $tag->name;

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