Sizing oEmbeds in WordPress

I have been a fan of the auto-embed feature in WordPress ever since it was introduced. Auto-embeds are powered by the oEmbed protocol. When you enter a YouTube link, the protocol grabs the embed from YouTube and displays it.

http://www.youtube.com/watch?v=yCENBce_dls

Being stuck with one size when inserting auto-embeds has been the only flaw I’ve encountered. You can, however, use a shortcode to set the maximum height and width of an individual video.

[embed width="460" height="400"]http://www.youtube.com/watch?v=esUMvBL3gnY[/embed]

This is great, but there is still an issue if you have different layout widths. If, for example, the width of your blog’s content area is 460px, but the single post template is wider, then you may want to set the embed width dynamically. I had to deal with this on a recent project and the solution was easier than I had imagined. All you have to do is add a filter to the embed_defaults() function and set the height and width values conditionally.

add_filter('embed_defaults', 'custom_embed_defaults');

function custom_embed_defaults($embed_size) {
    if (is_single()) { // Conditionally set max height and width
        $embed_size['width'] = 640;
        $embed_size['height'] = 600;
    } else {           // Default values
        $embed_size['width'] = 460;
        $embed_size['height'] = 600;
    }
    return $embed_size; // Return new size
}

Note: You usually don’t need worry about the height value as long as you
set it high enough. Most embeds are wider than they are tall.

I dropped this snippet in functions.php, but it could easily be turned into a plugin. Hope this help someone. Enjoy!

3 thoughts on “Sizing oEmbeds in WordPress

  1. Pingback: bsdeluxe » Removing the Height From WordPress Embeds

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>