Automatically Embedding Video Using Only the URL With the Help of oEmbed

One of my favorite functions of the WordPress editor is now the automatic embedding of video and other rich media by simply putting the URL on it’s own line. Really, it’s amazing!

Here is my rip of the WordPress code (found in the WP_Embed and WP_oEmbed classes) and assembled into a class named AutoEmbed.

It supports the following services (according to the WordPress Codex):

  • blip.tv
  • DailyMotion
  • Flickr (both videos and images)
  • FunnyOrDie.com
  • Hulu
  • Instagram
  • Qik
  • Photobucket
  • PollDaddy
  • Revision3
  • Scribd
  • SlideShare
  • SoundCloud
  • SmugMug
  • Twitter
  • Viddler
  • Vimeo
  • YouTube (only public and “unlisted” videos and playlists – “private” videos will not embed)
  • WordPress.tv (only VideoPress-type videos for the time being)

You can get the “gist” of it by looking below; the example is followed by the class definition.

Comments

  1. speedt_ouch says

    Hi.
    Thanks for sharing.
    I was looking for something like this to use on my codeigniter website i’m making.

  2. speedt_ouch says

    Hello again.
    I hope you can help.
    I use tinymce and when I copy and past a youtube link, tinymce places the string inside paragraphstags in my CMS, that is NOT wordpress

    So when I check the page, the string is not converted because of the paragraphs tags.

    If I edit mysql and delete the paragraphs tags and reload my that the video string in converted and embed correctly.

    Can you please provide a fix for the code also consider paragraphs tags?

    I checked wordpress and the code does get embeded if there is paragraphs tags also.

    Thanks again.

    • says

      Replace the parse and autoembed_callback functions with the following and I think you’ll get the result you desire:

          function parse( $content ) {
              return preg_replace_callback( '`^\s*(?:(https?://[^\s"]+))|(?:<p>(https?://[^\s"]+)</p>)\s*$`im', array( $this, 'autoembed_callback' ), $content );
          }
       
          function autoembed_callback( $match ) {
              if(isset($match[1]) && !empty($match[1])){
                  $url = $match[1];
              }elseif(isset($match[2]) && !empty($match[2])){
                  $url = $match[2];
              }
              $attr['discover'] = true;
              $return = $this->get_html( $url, $attr );
              return "\n$return\n";
          }

      Side note, the WordPress editor strips the <p/> tags and uses new lines instead. To test yourself, wrap something in <p/> tags in the Text view, then switch to Visual, and then back to Text; now your <p/> tags are gone. When it goes to display post content it uses wpautop() to add <p/> tags back in.

  3. speedt_ouch says

    Hi.
    Thank you very much for your reply!

    After I posted my questions here I searched a little and found that I was not the first with the tag issues.

    I found a suggested fix on stackoverflow:
    http://stackoverflow.com/questions/12115895/preg-replace-callback-matching-urls-in-html-paragraphs

    I changed your code with the suggested code from stackoverflow and got it working

    But now that you sent a fix I guess I will stick to your code with your fix instead :)

  4. shimpoul says

    Hi,
    When i put another link on the $content i don’t get them on the result ! like for images link, http://www.google.com for example and others …

    Can you give a fix for this ?

    And how i can embed this function to your code ?

    function media($str) {
    $str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr)
    {
        if(strpos($arr[0], 'http://') !== 0)
        {
            $arr[0] = 'http://' . $arr[0];
        }
        $url = parse_url($arr[0]);
     
        // images
        if(preg_match('#\.(png|jpg|gif)$#', $url['path']))
        {
            return '';
        }
        // youtube
        if(in_array($url['host'], array('www.youtube.com', 'youtube.com'))
          && $url['path'] == '/watch'
          && isset($url['query']))
        {
            parse_str($url['query'], $query);
            return sprintf('', $query['v']);
        }
        //links
        return sprintf('<a href="%1$s" rel="nofollow">%1$s</a>', $arr[0]);
    }, $str);
    return $str;
    }

    To get all non embed link a href=””……/a and display images links ?

    Thank you in advance.

      • shimpoul says

        Thank you so much for this helpful function !

        There a way to combine it with your code ?

        I made like this:

        function autoembed_callback( $match ) {
            $attr['discover'] = true;
            $return = $this->get_html( $match[1], $attr );
         
            if($return == "") {
                $return = $this->linkify($match[1], array('http', 'https'), array(), 'normal', true);
            }
         
            return "\n$return\n";
        }
  5. speedt_ouch says

    Hi.
    Once again I see your help if possible.
    I was wondering what would be the best way to add a custom class to make the videos responsive?

    I’m using boostrap for styling and I need to add two divs automatically for each video.

    http://getbootstrap.com/components/#responsive-embed

    I did some changes to the function fetch() and added some class=… code, but its never written in the html so obviously I’m not doing it right.

    Thanks in advance!

    • says

      The data2html() function is where you can modify the output for video/rich or wrap the output with an HTML tag. Depending on what HTML is returned by oEmbed you could use a str_replace or preg_replace to inject your class or other code. Hope that gives you a direction at least.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>