ワードプレスのwp_get_current_commenter関数の使用方法・解説

概要

wp_get_current_commenter関数は、現在のコメント投稿者情報を取得するための関数です。この関数は、コメントフォームでのデフォルト値を設定する際や、コメントのリストを表示する前にユーザーの情報を取得する際に便利です。一般的には以下のようなシナリオで使用されます。

  1. コメントフォームにユーザーの情報を自動入力する。
  2. コメントの投稿者情報をカスタマイズ表示する。
  3. 非ログインユーザーの情報を一時的に保存する。
  4. スパムチェックを行う際に投稿者の情報を確認する。
  5. コメント投稿後のメッセージを設計する際に利用する。
  6. コメントリストで他のユーザーと区別する情報を表示する。
  7. テーマやプラグインでカスタマイズしたコメントシステムを構築する。
  8. コメント投稿時に特定の条件を満たすユーザーの情報を取得する。

構文

wp_get_current_commenter();

パラメータ

この関数はパラメータを受け取ることはありません。

戻り値

戻り値は、現在のコメント投稿者の情報を含む配列です。具体的には、comment_author, comment_author_email, comment_author_url, comment_author_IPなどの情報が含まれます。

関連する関数

使用可能なバージョン

この関数は、WordPress 3.0.0以降で使用可能です。

コアファイルのパス

この関数は、wp-includes/comment.phpに含まれています。

サンプルコード

サンプルコード1: コメントフォームに情報を自動入力

$current_commenter = wp_get_current_commenter();
?>
<input type="text" name="author" value="<?php echo esc_attr($current_commenter['comment_author']); ?>" />
<input type="email" name="email" value="<?php echo esc_attr($current_commenter['comment_author_email']); ?>" />

このコードは、コメントフォームのauthoremailフィールドに現在のコメント投稿者の情報を自動入力します。

サンプルコード2: コメント投稿者情報のカスタム表示

$current_commenter = wp_get_current_commenter();
if (!empty($current_commenter['comment_author'])) {
    echo '<p>こんにちは、' . esc_html($current_commenter['comment_author']) . 'さん!</p>';
}

このコードは、現在のコメント投稿者の名前をカスタムメッセージとして表示します。

サンプルコード3: スパムチェックの条件

$current_commenter = wp_get_current_commenter();
if (strpos($current_commenter['comment_author_email'], 'example.com') === false) {
    // スパムではない場合の処理
}

このコードは、コメント投稿者のメールアドレスが特定のドメインでない場合にスパムではないと判断します。

サンプルコード4: コメント投稿後のメッセージ

add_action('comment_post', 'custom_comment_post_message');
function custom_comment_post_message($comment_ID) {
    $current_commenter = wp_get_current_commenter();
    echo 'ありがとうございます、' . esc_html($current_commenter['comment_author']) . 'さん!コメントが投稿されました。';
}

このコードは、コメントが投稿された後に確認メッセージを表示します。

サンプルコード5: コメントリストでの区別表示

$current_commenter = wp_get_current_commenter();
$comments = get_comments();
foreach ($comments as $comment) {
    if ($comment->comment_author_email == $current_commenter['comment_author_email']) {
        echo '<strong>' . esc_html($comment->comment_author) . '</strong> (あなたのコメント)';
    } else {
        echo esc_html($comment->comment_author);
    }
}

このコードは、現在のコメント投稿者のコメントを特別に強調表示します。

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

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

非推奨または削除されたバージョン

この関数は、特定のWordPressバージョンで非推奨または削除されることはありません。

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


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