Using WordPress ‘get_the_tags()’ PHP function

The get_the_tags() WordPress PHP function retrieves the tags for a post.

Usage

$post_tags = get_the_tags($post);

Parameters

  • $post (int|WP_Post) – Required. The post ID or object.

More information

See WordPress Developer Resources: get_the_tags()

Examples

$post_tags = get_the_tags();
if ($post_tags) {
    echo $post_tags[0]->name;
}

Print the tags of the current post (use within The Loop)

$post_tags = get_the_tags();
if ($post_tags) {
    foreach ($post_tags as $tag) {
        echo $tag->name . ', ';
    }
}

Show post tags with link and a custom separator

function wpdocs_show_tags() {
    $post_tags = get_the_tags();
    $separator = ' | ';
    $output = '';

    if (!empty($post_tags)) {
        foreach ($post_tags as $tag) {
            $output .= '<a href="' . esc_attr(get_tag_link($tag->term_id)) . '">' . $tag->name . '</a>' . $separator;
        }
    }

    return trim($output, $separator);
}

Get tags using post ID (no need for The Loop)

$post_tags = get_the_tags(24);
print_r($post_tags);
$post_tags = get_the_tags();
if (!empty($post_tags)) {
    echo '<ul>';
    foreach ($post_tags as $post_tag) {
        echo '<li><a href="' . get_tag_link($post_tag) . '">' . $post_tag->name . '</a></li>';
    }
    echo '</ul>';
}