Using WordPress ‘get_comment_text()’ PHP function

The get_comment_text() WordPress PHP function retrieves the text of the current comment.

Usage

get_comment_text($comment_id, $args);

Input:

$comment_id = 123;
$args = array();

echo get_comment_text($comment_id, $args);

Output:

This is a sample comment text.

Parameters

  • $comment_id (int|WP_Comment) – Optional. WP_Comment or ID of the comment for which to get the text. Default is the current comment.
  • $args (array) – Optional. An array of arguments. Default is an empty array.

More information

See WordPress Developer Resources: get_comment_text

Examples

Get the text of a specific comment

Get the text of a comment with the ID of 123.

$comment_id = 123;
$comment_text = get_comment_text($comment_id);
echo $comment_text;

Get the text of the current comment in a loop

Within the comment loop, get the text of the current comment.

if (have_comments()) {
    while (have_comments()) {
        the_comment();
        echo get_comment_text();
    }
}

Display all comments with their text

Loop through all comments and display their text.

$comments = get_comments();
foreach ($comments as $comment) {
    echo get_comment_text($comment);
}

Modify the comment text based on a condition

Use the get_comment_text filter to modify the text of comments with the ID 723 or 15.

add_filter('get_comment_text', 'wpdocs_comment', 10, 2);
function wpdocs_comment($text_content, WP_Comment $com) {
    if (!is_admin() && in_array($com->comment_ID, array(723, 15))) {
        $text_content = __('You\'ve Just Been Erased!');
    }
    return $text_content;
}

Display comment text with a custom format

Display the comment text with custom formatting by passing arguments to the function.

$args = array(
    'before' => '<strong>',
    'after' => '</strong>'
);

$comment_id = 123;
$comment_text = get_comment_text($comment_id, $args);
echo $comment_text;