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 post-tags-$tag->name>$tag->name</span>";
}
}
?>
The
I have added breaks the code. It simply returns
<span class="post-tags post-tags-tag3">tag3</span>
2
Answers
I got this answer from a friend and it fixed the problem
Basically you need to escape the apostrophes
Try this
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;