ワードプレスのget_adjacent_post_linkフィルタの使用方法・解説

概要

get_adjacent_post_link フィルタは、WordPressの投稿で関連する投稿のリンクを取得するために使用されます。このフィルタは、特定の投稿の直前または直後の投稿ページのリンクを取得する際にカスタマイズや拡張を行うために役立ちます。よく使われるシナリオには以下のようなものがあります。

  1. 投稿ナビゲーションのカスタマイズ
  2. カスタム投稿タイプの隣接投稿の取得
  3. 特定の条件に基づく投稿のフィルタリング
  4. 投稿メタデータの利用
  5. タグやカテゴリによる関連投稿の強調表示
  6. SEO対策としてのナビゲーションの改善
  7. 個々のテーマでのデザイン調整
  8. プラグインによる機能拡張

構文

add_filter('get_adjacent_post_link', 'my_custom_adjacent_post_link', 10, 4);

パラメータ

  • $output (string): 生成されるリンクのHTML。
  • $link (string): リンクのフォーマット。
  • $adjacent (object): 直前または直後の投稿オブジェクト。
  • $in_same_term (bool): 同じタームに属する投稿を取得するかどうか。

戻り値

  • 変更またはカスタマイズされたリンクのHTML。

関連する関数

フィルタの関連関数一覧

使用可能なバージョン

特になし。

コアファイルパス

wp-includes/link-template.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: 投稿ナビゲーションのカスタマイズ

add_filter('get_adjacent_post_link', 'custom_adjacent_post_link', 10, 4);
function custom_adjacent_post_link($output, $link, $adjacent, $in_same_term) {
    return '<div class="custom-navigation">' . $output . '</div>';
}

このサンプルは、隣接投稿リンクを <div class="custom-navigation"> でラップします。

サンプル 2: カスタム投稿タイプ名の追加

add_filter('get_adjacent_post_link', 'add_custom_post_type_name', 10, 4);
function add_custom_post_type_name($output, $link, $adjacent, $in_same_term) {
    return str_replace('href=', 'data-post-type="' . get_post_type($adjacent) . '" href=', $output);
}

このサンプルは、隣接投稿リンクにカスタム投稿タイプをデータ属性として追加します。

サンプル 3: 投稿メタデータの取得

add_filter('get_adjacent_post_link', 'add_post_meta_to_link', 10, 4);
function add_post_meta_to_link($output, $link, $adjacent, $in_same_term) {
    $meta_value = get_post_meta($adjacent->ID, 'my_meta_key', true);
    return str_replace('>' . $adjacent->post_title . '<', '>' . $meta_value . '<', $output);
}

このサンプルは、隣接投稿のタイトルを投稿メタの値で置き換えます。

サンプル 4: リンクの色を変更

add_filter('get_adjacent_post_link', 'change_link_color', 10, 4);
function change_link_color($output, $link, $adjacent, $in_same_term) {
    return str_replace('<a ', '<a style="color: red;" ', $output);
}

このサンプルは、隣接投稿リンクのテキスト色を赤に変更します。

サンプル 5: デバッグ用のログ出力

add_filter('get_adjacent_post_link', 'log_adjacent_post', 10, 4);
function log_adjacent_post($output, $link, $adjacent, $in_same_term) {
    error_log('Adjacent Post ID: ' . $adjacent->ID);
    return $output;
}

このサンプルは、隣接投稿のIDをApacheエラーログに記録します。

各サンプルはいずれも著作権フリーの内容です。

この関数について質問する


上の計算式の答えを入力してください