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

概要

get_the_author_linkフィルタは、投稿者のリンクを取得するために使用されるフックです。このフィルタは、WordPressテーマやプラグインで投稿者情報をカスタマイズする際によく使われます。ここでは、特に以下のような機能を実装する際に用いられることが多いです。

  1. 投稿者の表示名のカスタマイズ
  2. 投稿者リンクのスタイルの変更
  3. 投稿者情報ページへのリンクの変更
  4. SNSリンクの追加
  5. 投稿者のバイオグラフィーを含めたリンクの生成
  6. 投稿者のアバターをリンク内に表示
  7. 特定のユーザータイプによる異なるリンク生成
  8. 投稿者リンクのソーシャルメディアへのリダイレクト

構文

apply_filters( 'get_the_author_link', string $link, int $user_id, string $author, string $author_url );

パラメータ

  • $link: 投稿者の作成されたリンク。
  • $user_id: 投稿者のユーザーID。
  • $author: 投稿者の名前(表示名)。
  • $author_url: 投稿者のURL。

戻り値

フィルタを通過した後の投稿者リンク(カスタマイズされたリンク)。

関連する関数

関連する関数

使用可能なバージョン

このフィルタは、WordPress 2.0以降で使用可能です。

コアファイルのパス

wp-includes/link.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_the_author_link', 'custom_author_link', 10, 4 );
function custom_author_link( $link, $user_id, $author, $author_url ) {
    $author = strtoupper( $author );
    return str_replace( $author, $author, $link );
}

引用元: https://www.example.com/sample1

サンプルコード2: 投稿者リンクのCSSクラスを追加

投稿者リンクに特定のCSSクラスを追加するサンプルです。

add_filter( 'get_the_author_link', 'add_custom_class_to_author_link', 10, 4 );
function add_custom_class_to_author_link( $link, $user_id, $author, $author_url ) {
    $link = str_replace( '<a ', '<a class="custom-author-class" ', $link );
    return $link;
}

引用元: https://www.example.com/sample2

サンプルコード3: 投稿者画像を含める

このコードは、投稿者リンクにアバターを追加します。

add_filter( 'get_the_author_link', 'add_avatar_to_author_link', 10, 4 );
function add_avatar_to_author_link( $link, $user_id, $author, $author_url ) {
    $avatar = get_avatar( $user_id, 32 );
    return $avatar . ' ' . $link;
}

引用元: https://www.example.com/sample3

サンプルコード4: 投稿者のSNSリンクを追加

投稿者リンクにSNSプロフィールへのリンクを追加するサンプルです。

add_filter( 'get_the_author_link', 'add_social_link_to_author', 10, 4 );
function add_social_link_to_author( $link, $user_id, $author, $author_url ) {
    $social_url = 'https://twitter.com/' . $author; // Twitterリンク
    return $link . ' <a href="' . $social_url . '">Twitter Profile</a>';
}

引用元: https://www.example.com/sample4

サンプルコード5: 限定的なユーザータイプ用のリンク変更

特定のロールを持つユーザーに異なるリンクを生成するサンプルです。

add_filter( 'get_the_author_link', 'custom_link_for_specific_role', 10, 4 );
function custom_link_for_specific_role( $link, $user_id, $author, $author_url ) {
    $user = get_userdata( $user_id );
    if ( in_array( 'editor', (array) $user->roles ) ) {
        return '<strong>' . $link . '</strong>'; // 編集者用に強調表示
    }
    return $link;
}

引用元: https://www.example.com/sample5

非推奨情報

get_the_author_linkフィルタは、特定のバージョンで非推奨または削除されていません。常に使用可能です。

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


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