In some WordPress themes, we may need to retrieve the name of the first tag attached to a post, such as the “High Power” tag in the example below.

How do we implement that? Compared with retrieving all the post’s tags, it is only one extra step. We still use the same function, get_the_tags(), as shown below:
$tags = get_the_tags();
if ( $tags && ! is_wp_error( $tags ) ) {
$first_tag = $tags[0]; // 第一个标签对象
echo '<a href="' . get_tag_link( $first_tag->term_id ) . '">' . esc_html( $first_tag->name ) . '</a>';
}
If you need to get the first term from a custom taxonomy, the method is similar, but the function is slightly different.
$post_id = get_the_ID();
$terms = wp_get_post_terms( $post_id, 'my_taxonomy' ); // 换成你的 taxonomy 名称
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
$first_term = $terms[0]; // 第一个分类项对象
echo '<a href="' . get_term_link( $first_term ) . '">' . esc_html( $first_term->name ) . '</a>';
}
This is a fairly general method. If you replace my_taxonomy with post_tag, it gets the first tag. If you replace it with category, it gets the first category.
WordPress is a very powerful platform. Almost all of the content stored in its database can be accessed through clear functions, which makes development much easier. Before implementing a feature, it is worth checking the official documentation to see whether a similar function already exists.
