Unable to get get_the_tags() in WordPress Template

I am using this code to get the tags in my wordpress posts for a theme

`<?php
$posttags = get_the_tags();
if ($posttags) {
  foreach ($posttags as $tag) {
     $tagnames[count($tagnames)] = $tag->name;
  }
  $comma_separated_tagnames = implode(", ", $tagnames);
  print_r($comma_separated_tagnames);
}
?>`

The PROBLEM is that it is returning tags for “all posts” not just individual posts, and I think the problem is that if a post DOESNT have tags – it just inserts tags anyway.

Read More

Can anyone help modify this so:

  1. It return tags only for a post – not all tags
  2. If there are no tags for a post, dont return anything

P.S – Can check out here for the wordpress docs

Related posts

Leave a Reply

3 comments

  1. <footer class="entry-footer">
                        <?php //get all tags for the post
                        $t = wp_get_post_tags($post->ID);
                        echo "<p class='tags-list'>TAGGED WITH: ";
                        foreach ($t as $tag) {
                            $tag_link = get_tag_link($tag->term_id);
                        echo "<a href='$tag_link' class='used-tag' rel='tag'>".($tag->name)."</a>&nbsp;";
                        }
                        echo "</p>";
                        ?>
                        </footer>
    

    This is what I did, displays tags for each post in the loop.

  2. alright I hope this could help someone , I stuck on this issue for about hour
    trying to get tags of my post “so I can mix it with twitter share link ”
    the_tags(); function were useless since I use it out of WP loop , get_the_tag_list(); were perfect to me since it can include post id ,

    $postid = $wp_query->post->ID; 
    
    $posttags =  strip_tags( get_the_tag_list( ' ', '', '', "$postid" ) ) ;
    

    ^^ the above code I stripped html codes to get tag name without href link .

    this is the function use case :-

    get_the_tag_list( string $before = '', string $sep = '', string $after = '', int $id )