在 WordPress 內要取得文章的標籤,可以使用 get_the_tags() 這個函式,函式裡面可以帶入文章編號或是如果在 get_post() 之後就能直接使用。
取得之後就可以透過迴圈把內容顯示出來:
$posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; } }
var_dump($posttags) 會出現類似這樣的內容:
Array
(
[0] => WP_Term Object
(
[term_id] => 108
[name] => tag-1
[slug] => tag-1
[term_group] => 0
[term_taxonomy_id] => 109
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
[object_id] => 24
)
[1] => WP_Term Object
(
[term_id] => 109
[name] => tag-2
[slug] => tag-2
[term_group] => 0
[term_taxonomy_id] => 110
[taxonomy] => post_tag
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
[object_id] => 24
)
)
如果要取得 tag 的連結的話,則是使用 get_tag_link() ,所以如果我們要取得該標籤的列表頁面,就是像這樣:
<?php
if ($posttags):
foreach($posttags as $tag): ?>
<a href="<?=get_tag_link($tag->term_id)?>" class=""><?=$tag->name?></a>
<?php
endforeach;
endif;
?>
參考:
get_the_tags()
get_tag_link()