Disallow img tag in comments?

I have been looking quite a long time for a way to stop people from posting external images in comments i e

<img alt="my photo" src="http://example.co.uk/pic.jpg" />

and the image is displayed, without permission from the owner. This is hard coded somewhere in core but I can’t find a way to unset this behaviour. Thanks!

Related posts

2 comments

  1. You can strip images on display pretty easily.

    add_filter(
      'comment_text',
      function($comment) {
        $allowed_html = array(
            'a' => array(
            'href' => array(),
            'title' => array()
          ),
          'br' => array(),
          'em' => array(),
          'strong' => array()
        );
        return  wp_kses($comment, $allowed_html);
      }
    );
    

    That will strip any tags not listed in the provided array. To specifically strip images with links to external sources you need something more complicated.

    function strip_external_images($match) {
      if (empty($match)) return;
      $site = parse_url(get_site_url());
      $parsed = parse_url($match[1]);
      if (empty($parsed['host']) || $site['host'] !== $parsed['host']) {
        return '';
      } else {
        return $match[0];
      }
    }
    
    add_filter(
      'comment_text',
      function($comment) {
        $pattern = '|<img.*src="([^"]*)"[^>]+>|';
        return preg_replace_callback($pattern,'strip_external_images',$comment);
      }
    );
    

    That should allow users to add images to comments but only images hosted at same domain as the site itself.

  2. I added iframe to your first function to allow embeds from sites like youtube and instagram. I reckon that is a secure way? It works as intended now. I am not sure what your second function accomplishes, the end result is the same with or without it. Perhaps I wasn’t clear enough about what I wanted to accomplish in my original question? Thank you very much. I will accept your answer.

    add_filter(
    'comment_text',
    function($comment) {
    $allowed_html = array(
        'a' => array(
            'href' => array(),
            'title' => array()
            ),
        'br' => array(),
        'em' => array(),
        'strong' => array(),
        'iframe' => array(
            'src' => array(),
            'height' => array(),
            'width' => array()
            ),
    );
    return  wp_kses($comment, $allowed_html);
    }
    ); 
    

Comments are closed.