wp_transition_comment_status()


WordPressのwp_transition_comment_status()は、コメントのステータスが変更されたときに呼び出されるフックをトリガーするための関数です。

シンタックス

wp_transition_comment_status( string $new_status, string $old_status, WP_Comment $comment );

引数の説明:

  • $new_status (string) — コメントの新しいステータス (例: ‘approved’, ‘spam’, ‘trash’)
  • $old_status (string) — コメントの以前のステータス
  • $comment (WP_Comment) — 対象のコメントオブジェクト

例1: ステータス変更をログに記録

以下のコードは、コメントステータスが変更された際にログを記録します。

add_action( 'transition_comment_status', function( $new_status, $old_status, $comment ) {
    error_log( "コメントID {$comment->comment_ID} のステータスが {$old_status} から {$new_status} に変更されました。" );
}, 10, 3 );

例2: ステータス変更時にメールを送信

コメントのステータスが承認済みに変更されたときにメールを送信します。

add_action( 'transition_comment_status', function( $new_status, $old_status, $comment ) {
    if ( $new_status === 'approved' ) {
        wp_mail( 'admin@example.com', 'コメントが承認されました', "コメント内容: {$comment->comment_content}" );
    }
}, 10, 3 );

例3: スパムコメントの自動削除

ステータスがスパムに変更された際にコメントを自動削除します。

add_action( 'transition_comment_status', function( $new_status, $old_status, $comment ) {
    if ( $new_status === 'spam' ) {
        wp_delete_comment( $comment->comment_ID, true );
    }
}, 10, 3 );

例4: ステータス変更時にカスタムメタデータを更新

コメントのステータスが変更された際にカスタムメタデータを設定します。

add_action( 'transition_comment_status', function( $new_status, $old_status, $comment ) {
    update_comment_meta( $comment->comment_ID, 'last_status_change', current_time( 'mysql' ) );
}, 10, 3 );

例5: コメントの変更通知をフロントエンドに表示

ステータス変更時にフロントエンドに通知を表示するカスタムコード。

add_action( 'transition_comment_status', function( $new_status, $old_status, $comment ) {
    if ( $new_status !== $old_status ) {
        echo "<div>コメントID {$comment->comment_ID} が {$old_status} から {$new_status} に変更されました。</div>";
    }
}, 10, 3 );

注意点:

  • 関数を使用する際は適切なフックと条件を設定してください。
  • コメントオブジェクトのプロパティを利用する際は、データが正しく取得できているか確認してください。

関連機能: