The comments_array hook is a filter that allows developers to modify the array of comments returned by the get_comments() function. This hook is useful for customizing the output of comment sections in WordPress, such as displaying comments in a specific order or filtering out certain comments based on their content.
When this hook is called, it passes an array of comment objects as its parameter. Developers can use this array to make modifications to the comments, such as changing their order or filtering out specific comments based on their content.
Here’s an example usage code for the comments_array hook:
function modify_comments_array( $comments ) {
// Loop through the comments and modify them as needed
foreach( $comments as $comment ) {
// Change the comment content
$comment->comment_content = str_replace( 'badword', 'goodword', $comment->comment_content );
}
// Return the modified comments array
return $comments;
}
add_filter( 'comments_array', 'modify_comments_array' );
In this example, we’re using the comments_array hook to modify the content of each comment in the array. Specifically, we’re replacing any instances of the word "badword" with "goodword" in the comment content. This could be useful for filtering out comments that contain inappropriate language.