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

概要

get_comment_textフィルタは、コメント文を取得する際にその内容を変更するためのフックです。このフィルタを使用することで、コメントのテキストを動的に加工したり、特定の条件に応じて変更を加えたりすることが可能になります。具体的には以下のような機能を実装する際によく使われます。

  1. コメント内のURLを自動的にリンクに変換する。
  2. コメントテキストの特定の単語を置換する(例:特定のキーワードを強調)。
  3. スパムフィルターを適用し、特定のテキストを削除する。
  4. コメントが特定の条件を満たす場合にマークアップを追加する。
  5. コメントの長さに応じて省略表示を実施する。
  6. 特定のユーザーのコメントの内容をカスタマイズする。
  7. 同一の内容のコメントを重複して表示しないようフィルタリングする。
  8. コメントの内容にHTMLエスケープを追加する。

構文

add_filter( 'get_comment_text', 'callback_function', 10, 2 );

パラメータ

  • $comment_text (string): 取得するコメントのテキスト。
  • $comment (WP_Comment): コメントオブジェクト。

戻り値

  • (string)フィルタされたコメントテキスト。

関連する関数

使用可能なバージョン

  • WordPress 2.0以降で使用可能。

コアファイルのパス

  • /wp-includes/comment.php

サンプルコード

サンプルコード1: コメント内のURLをリンクに変換

add_filter( 'get_comment_text', 'make_urls_clickable', 10, 2 );

function make_urls_clickable( $comment_text, $comment ) {
    return make_clickable( $comment_text );
}

このコードは、コメント内に含まれるURLを自動的にリンクに変換します。

サンプルコード2: 特定の単語を置換

add_filter( 'get_comment_text', 'replace_keyword', 10 );

function replace_keyword( $comment_text ) {
    return str_replace( 'WordPress', 'WP', $comment_text );
}

このコードは、コメント内の「WordPress」という単語を「WP」に置き換えます。

サンプルコード3: スパムフィルタの適用

add_filter( 'get_comment_text', 'filter_spam', 10 );

function filter_spam( $comment_text ) {
    $spam_words = array( 'spam', 'advertisement' );
    foreach ( $spam_words as $word ) {
        if ( stripos( $comment_text, $word ) !== false ) {
            return '';
        }
    }
    return $comment_text;
}

このコードは、指定されたスパム用語が含まれるコメントを空文字に置き換えます。

サンプルコード4: コメントテキストのマークアップ追加

add_filter( 'get_comment_text', 'add_markup_to_comments', 10 );

function add_markup_to_comments( $comment_text ) {
    return '<strong>' . esc_html( $comment_text ) . '</strong>';
}

このコードは、コメント文を強調表示するために、テキストを <strong> タグで囲みます。

サンプルコード5: コメントの長さに応じた処理

add_filter( 'get_comment_text', 'shorten_long_comments', 10 );

function shorten_long_comments( $comment_text ) {
    if ( strlen( $comment_text ) > 100 ) {
        return substr( $comment_text, 0, 100 ) . '...';
    }
    return $comment_text;
}

このコードは、コメントが100文字を超える場合に、省略記号を追加してテキストを短縮します。

この関数のアクションでの使用可能性

アクション 使用可能性
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

非推奨例

get_comment_textフィルタは、特定のバージョンで非推奨または削除された例はありません。

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


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