wp_insert_comment()


WordPress関数wp_insert_comment()は、新しいコメントをプログラムで作成し、データベースに挿入するために使用されます。

構文

wp_insert_comment( array $commentdata );

引数の説明

  • $commentdata (array) — 挿入するコメントデータの連想配列。以下のキーを含むことができます:
    • comment_post_ID (int) — コメントが関連付けられる投稿のID。
    • comment_author (string) — コメントの投稿者名。
    • comment_author_email (string) — コメント投稿者のメールアドレス。
    • comment_author_url (string) — コメント投稿者のウェブサイトURL。
    • comment_content (string) — コメント本文。
    • comment_approved (int|string) — コメントの承認ステータス。1は承認済み、0は保留中。

例 1: 基本的なコメントの挿入

wp_insert_comment( array(
    'comment_post_ID' => get_the_ID(),
    'comment_author' => 'テストユーザー',
    'comment_content' => 'これはテストコメントです。',
    'comment_approved' => 1,
) );

例 2: 投稿者情報を含むコメントの挿入

wp_insert_comment( array(
    'comment_post_ID' => get_the_ID(),
    'comment_author' => '山田太郎',
    'comment_author_email' => 'yamada@example.com',
    'comment_author_url' => 'https://example.com',
    'comment_content' => 'リンク付きのテストコメント。',
    'comment_approved' => 1,
) );

例 3: 未承認のコメントを挿入

wp_insert_comment( array(
    'comment_post_ID' => get_the_ID(),
    'comment_author' => '未承認ユーザー',
    'comment_content' => 'このコメントは未承認です。',
    'comment_approved' => 0,
) );

例 4: カスタム投稿タイプへのコメント挿入

wp_insert_comment( array(
    'comment_post_ID' => get_post( 'カスタム投稿ID' )->ID,
    'comment_author' => 'カスタムユーザー',
    'comment_content' => 'これはカスタム投稿タイプへのコメントです。',
    'comment_approved' => 1,
) );

例 5: 現在のユーザーをコメント投稿者として設定

$current_user = wp_get_current_user();
wp_insert_comment( array(
    'comment_post_ID' => get_the_ID(),
    'comment_author' => $current_user->display_name,
    'comment_author_email' => $current_user->user_email,
    'comment_content' => '現在のユーザーによるコメント。',
    'comment_approved' => 1,
) );

注意点

  • wp_insert_comment()を使用する際は、必要に応じてsanitize_text_field()esc_html()を利用してデータのサニタイズとエスケープを行ってください。

関連機能: