wp_get_post_tags()


WordPressのwp_get_post_tags()関数は、指定した投稿に関連付けられているタグを取得するための関数です。

構文

wp_get_post_tags( int $post_id, array $args = array() );

引数の説明:

  • $post_id (int) — タグを取得したい投稿のIDを指定します。
  • $args (array) — オプションの引数。カスタム設定を指定するために使用します。

例1: 投稿のタグを取得して表示する

以下のコードは、投稿のすべてのタグを取得して表示します。

<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
foreach ($tags as $tag) {
    echo $tag->name . '<br>';
}
?>

例2: 投稿のスラッグのみを取得して表示する

スラッグを取得し、それを出力します。

<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
foreach ($tags as $tag) {
    echo $tag->slug . '<br>';
}
?>

例3: 投稿のタグをカンマ区切りで表示する

タグをカンマ区切りで1行にまとめて表示します。

<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
$tag_names = array_map(function($tag) { return $tag->name; }, $tags);
echo implode(', ', $tag_names);
?>

例4: 特定の条件に基づいてタグをフィルタリングする

特定のスラッグを持つタグのみを表示します。

<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
foreach ($tags as $tag) {
    if ($tag->slug === 'example-slug') {
        echo $tag->name . '<br>';
    }
}
?>

例5: タグのリンクを生成して表示する

タグにリンクを追加して出力します。

<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
foreach ($tags as $tag) {
    echo '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a><br>';
}
?>

注意事項

wp_get_post_tags()関数を使用する際、$post_idが正しい値であることを確認してください。不適切な値を渡すと、正しい結果が得られない可能性があります。


関連機能: