在有些WordPress主题中,我们可能需要获取文章的第一个标签名称,如下图中的“大功率”标签。

怎么实现这个需求呢?其实相比获取所有的文章标签,只多了一小步,使用的是同样的函数——get_the_tags()
,代码如下:
$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>';
}
如果需要获取第一个自定义分类方法项目,方法是类似的,只不过使用的函数不太一样。
$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>';
}
这是一种比较通用的方法,把 my_taxonomy 换成「post_tag」,就是获取第一个标签,换成「category」就是获取第一个分类。
WordPress是一个功能很强大的平台,数据库中的所有内容,几乎都有明确的函数可以调用,者就大大方便了我们的开发过程,要实现一个功能之前,不妨上官方文章搜索一下有没有类似的函数。