Tutorial and simple example for text widget filter in wordpress, learn text widget filter, embed youtube video in text widget easily and without plugin.

What is Text Widget Filter

Using widget_text filter, we can do more options in text widget, for example we can add class to links or embed youtube video easily, and we can display any shortcode in text widget without plugin.


This is example to embedding youtube video easily in text widget, copy function code and paste it in your functions.php file, function code:

function WPTime_embed_youtube_in_text_widget($text){
    /* Function By Qassim Hassan - https://wp-time.com */

    $youtube_regex = '/(https?:\/\/youtube.com\/watch)|(www.youtube.com\/watch)|(youtube.com\/watch)|(https?:\/\/www.youtube.com\/watch)|(https?:\/\/youtu.be)|(www.youtu.be)|(youtu.be)|(https?:\/\/www.youtu.be)/'; // check if correct youtube link or not.
    $youtube_exclude = '/("https?:\/\/youtube.com\/watch)|("www.youtube.com\/watch)|("youtube.com\/watch)|("https?:\/\/www.youtube.com\/watch)|("https?:\/\/youtu.be)|("www.youtu.be)|("youtu.be)|("https?:\/\/www.youtu.be)/'; // check if <a href=""> html tag or not.
    $height = '300'; // video height is 300, change it if you want.

    if( preg_match($youtube_regex, $text) and !preg_match($youtube_exclude, $text) ){
        $protocol = array('http://', 'https://', 'www.', 'youtube.com', 'youtu.be', 'embed', 'watch?v=', '/'); // remove all thing.
        $str_replace = str_replace($protocol, '', $text);
        $video_id = preg_replace( array('/[^&?]*?=[^&?]*/', '/[(&)]/'), '', $str_replace ); // clean youtube video ID.
        $text = '<iframe style="width:100%!important;max-width:100%!important;display:block!important;height:'.$height.'px;" src="http://youtube.com/embed/'.$video_id.'" allowfullscreen></iframe>'; // youtube iframe video with responsive style!

    return $text; // display youtube video in text widget.
add_filter('widget_text', 'WPTime_embed_youtube_in_text_widget');

Now use “Text Widget”, and in “Content” field, enter youtube video link only, for example:

Text Widget Filter In WordPress


You can use The Media Widget plugin.