How to edit WordPress comment before the page is rendered?

Viewed 82

In WordPress, you can do the following to edit the content of an article before the page is loaded:

add_filter('the_content', 'edit_content');
function edit_content($content) {
    // edit $content
    return $content;
}

How can I achieve the same thing but for comments?

1 Answers

You add a filter to the comment_text hook, similar to how you do it with the_content hook. This hook lets you change the comment text that is displayed using comment_text() in your template.

For example:

add_filter( 'comment_text', 'edit_comment_text', 99);
function edit_comment_text( $comment_text, $commentObject, $args ) {
    // edit the text....
    return $comment_text;
}

Note that you might need to set the priority in add_filter to a high number so that it runs after WP's own filters first - I used 99 above.

You can see in the WP Developer Code Reference for comment_text that the 3 parameters the filter gets are:

  • $comment_text (string) - Text of the current comment.
  • $commentObject (WP_Comment|null) - The comment object. Null if not found.
  • $args (array) - An array of arguments.
Related