在有些WordPress主題中,我們可能需要獲取文章的第一個標簽名稱,如下圖中的“大功率”標簽。

怎么實現(xiàn)這個需求呢?其實相比獲取所有的文章標簽,只多了一小步,使用的是同樣的函數(shù)——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>';
}
如果需要獲取第一個自定義分類方法項目,方法是類似的,只不過使用的函數(shù)不太一樣。
$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是一個功能很強大的平臺,數(shù)據(jù)庫中的所有內(nèi)容,幾乎都有明確的函數(shù)可以調(diào)用,者就大大方便了我們的開發(fā)過程,要實現(xiàn)一個功能之前,不妨上官方文章搜索一下有沒有類似的函數(shù)。
