概要
wp_get_post_tags関数は、指定された投稿の投稿記事の投稿タグ情報を取得するために使用されます。この関数は、WordPressの投稿に関連するタグを簡単に取得したいときに役立ちます。主に次のような機能を実装する際によく使われます。
- 投稿のタグ一覧を表示する
- 投稿のタグを基に関連投稿を表示する
- タグに基づくフィルタリング機能を実装する
- タグクラウドを作成する
- SEO目的でのタグ情報を活用する
- 投稿のメタ情報をカスタマイズする
- タグの情報をサイドバーやウィジェットに表示する
- タグを使用したカスタムクエリの実行
構文
wp_get_post_tags( $post_id, $args );
パラメータ
post_id(int) – 投稿のID。現在の投稿に対してタグを取得する場合は省略可。$args(array) – 可選の引数で、orderby,order,fields,numberなどを指定できる。
戻り値
- タグ情報の配列。タグのオブジェクトが含まれる。
関連する関数
使用可能なバージョン
wp_get_post_tags関数はWordPressバージョン4.2以降で使用可能です。
コアファイルのパス
wp-includes/taxonomy.php
この関数のアクションでの使用可能性
| アクション | 使用例 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | |
| register_sidebar | |
| wp_loaded | 〇 |
| send_headers | |
| parse_query | |
| pre_get_posts | 〇 |
| wp | 〇 |
| template_redirect | |
| get_header | |
| wp_head | 〇 |
サンプルコード
サンプルコード 1: 投稿のタグを取得して表示
$post_id = 1; // 取得したい投稿のID
$tags = wp_get_post_tags( $post_id );
if ( !empty( $tags ) ) {
foreach ( $tags as $tag ) {
echo '<li>' . esc_html( $tag->name ) . '</li>';
}
}
このコードは特定の投稿IDの投稿タグを取得し、それらのタグをリストとして表示します。
出典: WordPress Codex
サンプルコード 2: 現在の投稿のタグを取得
$tags = wp_get_post_tags( get_the_ID() );
foreach ( $tags as $tag ) {
echo $tag->name . ' ';
}
このコードは、現在表示している投稿のIDを使用して、その投稿のタグを取得し、タグ名をスペースで区切って表示します。
出典: WordPress Plugin Handbook
サンプルコード 3: タグに基づいたクエリの実行
$tags = wp_get_post_tags( $post_id );
$tag_ids = wp_list_pluck( $tags, 'term_id' );
$args = array(
'tag__in' => $tag_ids,
'post_type' => 'post',
'posts_per_page' => 5,
);
$related_posts = new WP_Query( $args );
このコードは、特定の投稿から関連タグを取得し、それに基づいて関連投稿をクエリします。
出典: WPBeginner
サンプルコード 4: 投稿タグの数を取得
$tags = wp_get_post_tags( $post_id );
$count = count( $tags );
echo 'この投稿には ' . $count . ' 個のタグがあります。';
このコードは、特定の投稿に関連するタグの数を取得して表示します。
出典: WordPress Support
サンプルコード 5: タグ情報をカスタマイズ
$args = array(
'orderby' => 'name',
'order' => 'ASC',
);
$tags = wp_get_post_tags( $post_id, $args );
foreach ( $tags as $tag ) {
echo '<span>' . esc_html( $tag->name ) . '</span>, ';
}
このコードは、タグを名前で並べ替えて表示します。
出典: WPExplorer