Simple wordpress function to display image in wordpress text widget without plugin and without html tags, easy to use and seo ready and compatible with fancy lightbox plugin.

How To Display Image In Widget

Using widget_text filter, we will display image in “Text” widget without plugin and without HTML tags, image will be SEO ready and compatible with fancy lightbox plugin, using widget_text filter, we can do more, for example we can embed youtube video in “Text” widget easily, and we can display any shortcode in “Text” widget.

Display Image Function

Copy function code and paste it in your functions.php file, function code:

function WPTime_add_image_to_text_widget($text){
    /*Function By Qassim Hassan - https://wp-time.com */
    if( preg_match('/(im:)+(https?:\/\/)+[\pL_]/', $text) ){
        $website_link = get_option('siteurl');
        $domain = str_ireplace('www.', '', parse_url($website_link, PHP_URL_HOST));
        $regex = "/($domain)/";
        $image = str_replace('im:', '', $text);

        if( !preg_match($regex, $image) ){
            $rel = ' rel="nofollow"';
            $target = ' target="_blank"';
        }else{
            $rel = null;
            $target = ' target="_blank"';
        }

        $the_text = '<a'.$rel.$target.' href="'.$image.'"><img src="'.$image.'"></a>';
    }

    else{
        $the_text = $text;
    }

    return $the_text;

}
add_filter('widget_text', 'WPTime_add_image_to_text_widget');

Usage

Use “Text” widget, and in “Content” field, enter “im:” before your image link, for example:

im:https://wp-time.com/my-image.jpeg

Display Image In WordPress Widget

Now will be display image in “Text” widget and will be compatible fancy lightbox plugin automatically, if your image link is “external” will be add rel=”nofollow” for SEO.

Note

Enter one image link in “Text” widget only, if you want two images or more than image, drag and drop “Text” widget again.