wordpress
WordPress投稿ページでタグ別のページナビを付ける
最終更新日: 2025年2月19日
要件は、カテゴリーはそれで使うが、タグでカテゴリーより絞った投稿群があるのでそれに対するページナビが要る、というもの。
用途はあまりない、故に忘れるので備忘。
<?php
$post_id = get_the_ID();
$tags = wp_get_post_tags($post_id);
if (!empty($tags)) {
// 最初のタグのIDを取得
$tag_id = $tags[0]->term_id;
// 同じタグを持つ投稿を取得
$query = new WP_Query(array(
'tag_id' => $tag_id,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => -1, // すべて取得
'fields' => 'ids' // 投稿IDのみ取得(メモリ消費を抑える)
));
$tagged_posts = $query->posts;
if (!empty($tagged_posts)) {
// 現在の投稿の位置を特定
$post_index = array_search($post_id, $tagged_posts, true);
if ($post_index !== false) {
$prev_post_id = $tagged_posts[$post_index - 1] ?? null;
$next_post_id = $tagged_posts[$post_index + 1] ?? null;
if ($prev_post_id || $next_post_id) {
echo '<nav class="pagination">';
if ($prev_post_id) {
echo '<a href="' . get_permalink($prev_post_id) . '" class="prev">' . esc_html(get_the_title($prev_post_id)) . '</a>';
}
if ($next_post_id) {
echo '<a href="' . get_permalink($next_post_id) . '" class="next">' . esc_html(get_the_title($next_post_id)) . '</a>';
}
echo '</nav>';
}
}
}
wp_reset_postdata();
}
?>
一致するタグの要件は、1投稿1タグがベスト。複数ある場合は最初のタグになるので、投稿毎ついているタグが異なると精度を欠くと思う。
複数使用でという場合はタグの抽出・指定を接頭辞でもつけてそれでやるとかかな。