0
  $tags = get_tags(array(
    'hide_empty' => false
  ));
  echo '<ul>';
    foreach ($tags as $tag) {
      echo '<li>' . $tag->name . '</li>';
    }
  echo '</ul>';

enter image description here

The above code is an excerpt of code in content-single.php Everything works fine, but

In the single post, the tag is an individual feature. This is generating an entire tag list on all single posts. How can I put a constraint so that on single posts pages only those tags are fetched, which are relevant and associated with that stand-alone single post?

2
  • 1
    PS: Just so you know, you could actually use get_tags() to get the tags assigned to specific post(s) only by using the object_ids argument, e.g. get_tags( [ 'object_ids' => get_the_ID() ] ), but get_the_tags() is easier if getting the tags for a single post only. :)
    – Sally CJ
    Aug 7, 2021 at 18:43
  • 1
    You have very deep knowledge. You can help people like us by creating a paid video course on udemy.com
    – WordCent
    Aug 8, 2021 at 7:16

1 Answer 1

1

If you want to get the tags (taxonomy: post_tag) for a specific post only, then you can use get_the_tags().

Excerpt from the documentation:

This function returns an array of objects, one object for each tag assigned to the post. If this function is used in The Loop, then no ID need be passed.

This function does not display anything; you should access the objects and then echo or otherwise use the desired member variables.

So in your code, you just need to replace this part:

  $tags = get_tags(array(
    'hide_empty' => false
  ));

with this:

  $tags = get_the_tags();

However, note that get_the_tags() may return a false or a WP_Error instance, so make sure to check if the $tags is a valid array. For example,

$tags = get_the_tags();

if ( is_array( $tags ) && ! empty( $tags ) ) {
    echo '<ul>';
    foreach ($tags as $tag) {
        echo '<li>' . $tag->name . '</li>';
    }
    echo '</ul>';
}

And actually, if you just want to display a HTML list (e.g. an UL) with tag names and links, then you can simply use the_tags() like so:

<?php the_tags( '<ul><li>', '</li><li>', '</li></ul>' ); ?>
1
  • 1
    It perfectly works, and also thank you so much for the extra credit knowledge.
    – WordCent
    Aug 12, 2021 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.