Freddy
Freddy

Reputation: 867

Using the_tags() function to display two tags as list elements

I'm trying the format the_tags WordPress function to display the tag text in an li. But encountering issues as no li is being rendered:

I've tried to format the_tags() like so:

<?php the_tags( $before, $sep, $after ); ?> 

Where (from the codex):

$before (string) Text to display before the actual tags are displayed.

$sep (string) Text or character to display between each tag link.

$after (string) Text to display after the last tag.

Here is my current approach:

$tags = the_tags();

if ($tags) {
    foreach($tags as $tag) {
        $count++;
        the_tags('','<li></li>', '');
        // echo '
        //  <li class="postLabel__tags">
        //      <a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a>
        //  </li>';
        if( $count >= 2 ) break; // only show 2 tags
    }
}

With the above, it prints out Tags: tag1, tag2. I don't want the "Tags:" text to be there and neither the comma. Unsure why the_tags('','<li></li>', ''); does not resolve this?

And the rendered HTML markup of the above is the following:

<a href="#" rel="tag">tag1</a>
", "
<a href="#" rel="tag">tag2</a>

Whereas I want it to be:

<li class="postLabel__tags"> 
    <a href="#" rel="tag">tag1</a>
</li>

<li class="postLabel__tags"> 
    <a href="#" rel="tag">tag2</a>
</li>

Upvotes: 1

Views: 540

Answers (1)

u_mulder
u_mulder

Reputation: 54831

the_tags() echoes list of tags. And returns nothing, so $tags variable is empty.

Your code should be reduced to:

the_tags(
    '<li class="postLabel__tags">',
    '</li><li class="postLabel__tags">', 
    '</li>'
);

To get tags as a list and control outputting them manually use get_the_tags();.

Upvotes: 1

Related Questions