You can do that by using the comment_text
filter. It runs for each comment, so with some regex you can find all links in the comment and loop through them. You make one more check to make sure the link has an image extension (jpg, jpeg, png, etc). If it does, we can embed it in the comment.
Here’s an example of that :
function display_images_in_comments($comment_text) {
// The regular expression for URL
$pattern = '/(https?:\/\/[^\s]+)/i';
// Find matches
if (preg_match_all($pattern, $comment_text, $matches)) {
foreach ($matches[0] as $match) {
// quotes might break the image url, so we remove them
$match = str_replace('"', '', $match);
$match = str_replace("'", '', $match);
// we check if the link is an image by checking the extension of the file
$extensions = array('jpg', 'jpeg', 'gif', 'png', 'svg');
$url_extension = pathinfo(parse_url($match, PHP_URL_PATH), PATHINFO_EXTENSION);
// if the link is an image, we embed it in the comment
if (in_array($url_extension, $extensions)) {
$comment_text .= "<img src="https://wordpress.stackexchange.com/questions/416243/$match"/>";
}
}
}
return $comment_text;
}
add_filter('comment_text', 'display_images_in_comments');
You’ll need to add some styling to the images, but it works.