How to Allow Images Instead of URL in WordPress Comments?


By default, the URLs in the comment are kept as they are. If a user put directly an image URL, it would be nice to replace the URL with the actual HTML img tag. Add the following piece of PHP code in your wordpress theme functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// empty - allow all posts, otherwise, put post IDs joined by comma
define('ALLOW_POSTS', '');
function helloacm_allow_comment_image( $comment ) {
    $post_ID = $comment["comment_post_ID"];
    $allow_posts = ALLOW_POSTS ? explode(',', ALLOW_POSTS) : array();
    if(empty($allow_posts) || in_array($post_ID, $allow_posts)){
        global $allowedtags;
        $content = $comment["comment_content"];
        $content = preg_replace('/(https?:\/\/\S+\.(?:jpg|png|jpeg|gif|bmp))+/','<img  title="$0 How to Allow Images Instead of URL in Wordpress Comments? wordpress " decoding="async" src="$0"  alt="$0 How to Allow Images Instead of URL in Wordpress Comments? wordpress "  />',$content);
        $allowedtags['img'] = array('src' => array (), 'alt' => array ());
        $comment["comment_content"] = $content;
    }
    return $comment;
}
add_filter('preprocess_comment', 'helloacm_allow_comment_image');
// empty - allow all posts, otherwise, put post IDs joined by comma
define('ALLOW_POSTS', '');
function helloacm_allow_comment_image( $comment ) {
    $post_ID = $comment["comment_post_ID"];
    $allow_posts = ALLOW_POSTS ? explode(',', ALLOW_POSTS) : array();
    if(empty($allow_posts) || in_array($post_ID, $allow_posts)){
        global $allowedtags;
        $content = $comment["comment_content"];
        $content = preg_replace('/(https?:\/\/\S+\.(?:jpg|png|jpeg|gif|bmp))+/','<img  title="$0 How to Allow Images Instead of URL in Wordpress Comments? wordpress " decoding="async" src="$0"  alt="$0 How to Allow Images Instead of URL in Wordpress Comments? wordpress "  />',$content);
        $allowedtags['img'] = array('src' => array (), 'alt' => array ());
        $comment["comment_content"] = $content;
    }
    return $comment;
}
add_filter('preprocess_comment', 'helloacm_allow_comment_image');

We use a regular expression to find image URLs (ending with extensions jpg/png/jpeg/gif/bmp), and replace with the HTML img tag. We also have to allow the IMG tag in the comment section, in order to display it correctly. The above function has to be added to the filter preprocess_comment which is invoked before a comment is inserted into the database.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
280 words
Last Post: Interview Question: Construct Evenly-Distribution Rand7 based on Rand5
Next Post: How to Read Local Files using HTML5 FileReader?

The Permanent URL is: How to Allow Images Instead of URL in WordPress Comments?

Leave a Reply