I'm looking for a way to display the images when the commenter adds a simple link to this image (without plugin, without upload, nor activate TinyMCE). For now, when the commenter adds a link to an image (hosted on Postimg for example), there is just the link that is displayed, but I'm looking for a way to make the image display. Any idea? Thanks.

1 Answer 1


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='$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.

  • Wow! That's a nice approach. I'm going to try this as soon as I can. Thank you for this!
    – dragoweb
    Commented May 24, 2023 at 9:42
  • It works great! Thanks a lot Alex. I was even able to add a lightbox ^^
    – dragoweb
    Commented May 24, 2023 at 11:39
  • There are some risks without proper sanitization. The extension 'sensing' is not foolproof. A malware'd link could be executed on the visitor's system - or executed on your system. Make sure that you properly sanitize the links before displaying. There have been malware attacks with malware'd links. So - there is a possible 'Danger, Wil Robinson' issue if not done properly and carefully. Commented May 25, 2023 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.