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>' ); ?>