How to Enable WordPress Embeds on Custom Fields

July 27, 2012 — 5

Starting in Version 2.9 WordPress added a super cool feature that lets you embed videos, images and other media by simply adding the source url in the post. So for example you could at the url “https://www.youtube.com/watch?v=PaUFSW3bxF8″ and the video would be automatically added to your post. WordPress currently support auto-embeds from these sources:


You can add more sources programmatically or with a plugin called Embedly.

I wanted to this feature to my Coming Soon plugin but it was not obvious on how to do so. I started hunting down the function that enabled this functionality on the post by searching for all the filters that ran on the template tag “the_content”. I found that on line 1056 in the file /wp-includes/media.php the following code was called:

 
// Attempts to embed all URLs in a post
if ( get_option('embed_autourls') )
    add_filter( 'the_content', array(&$this, 'autoembed'), 8 );

The method autoembed is part of a class called WP_Embed which is defined as “API for easily embedding rich media such as videos and images into content.”

So this was the function I need to pass my custom field content into to get the auto embed urls. I discover this was class was in the $GLOBALS array. so now all I had to do was call the method. Here’s the code.

 
if(isset($GLOBALS['wp_embed']))
    $content = $GLOBALS['wp_embed']->autoembed($content);

This would run your content through the oEmbed process of getting the html for the media urls.

If anyone knows of a better way to do this please let me know in the comments.

  • http://blog.nicolas-juen.fr Raherian

    There is an other solution : apply_filters( ‘the_content’, $content ); . But if you have some scripts and div and stuff using the ‘the_content’ filter then they will appear after your embed element.

    • John Turner

      Nice, haven’t thought of that approach. But true, anything attached to that filter would run as well.

  • http://www.facebook.com/kgreeff Ken Greeff

    Legend! Searched for hours on how to do this, thanks mate!

  • Tevya Washburn – FS

    I’m wondering if anyone knows of an easy way to set the width for all oembeds on the site? Prior to 3.5, WP had a width and height setting. I always just set the width to the width of the main content area of the blog, and left the height blank (the opposite of the default). But now there’s no such setting. On most blogs videos and other content embed narrower than the main content area of posts/pages and it looks sloppy. I’m completely unsure why they removed it, and am wishing for an easy way to get it back, without using the shortcode each time (which kinda defeats the purpose in my mind).

    • http://johndturner.com John Turner

      You can use fitvid.js for videos and it will autosize to the container that it’s in. For images you should be able to set 100% max-width to fit the container.