WP-Mix

A fresh mix of code snippets and tutorials

WordPress oEmbed Tricks

Ahh yeah, here are some sweet little code snippets to customize the default WordPress oEmbed functionality. Techniques include modifying default oEmbed size, markup, as well as enabling oEmbed for Post Excerpts and Custom Fields.

Customize oEmbed video size

This snippet hooks into embed_defaults and sets the video size to 600×450. Add to functions.php or via plugin.

// Customize oEmbed video size
function shapeSpace_oembed_size() { 
	return array('width' => 600, 'height' => 450);
}
add_filter('embed_defaults', 'shapeSpace_oembed_size');

You can set the width and height values to whatever is required. You can also set the video width using the $content_width global variable:

function shapeSpace_content_width() {
	$GLOBALS['content_width'] = 600; // px
}
add_action('after_setup_theme', 'shapeSpace_content_width', 0);

Or more simply:

if (!isset($content_width)) $content_width = 600; // px

Adding either of those snippets to functions.php would set the default content width to 600px, which would be used as the width for oEmbed videos, among other things.

Customize oEmbed markup

Here we are customizing the default oEmbed markup by wrapping it with a <div> classed with .oembed. Add to functions.php or via plugin.

// Customize oEmbed markup
function shapeSpace_oembed_html($html, $url, $attr, $post_id) {
	return '<div class="oembed">'. $html .'</div>';
}
add_filter('embed_oembed_html', 'shapeSpace_oembed_html', 99, 4);

You can change the markup to whatever is required, and/or customize the $html variable as desired.

Enable oEmbed on Post Excerpts

By default WordPress does not filter Post Excerpts with oEmbed. To enable it, you can add the following snippet to your theme’s functions file, or add via simple custom plugin.

// Enable oEmbed on Post Excerpts
add_filter('the_excerpt', array($GLOBALS['wp_embed'], 'autoembed'), 9);

Nothing else to do here, just plug-&-play and done.

Enable oEmbed on Custom Fields

By default WordPress does not filter Custom Fields with oEmbed. To enable it, you can add the following snippet to your theme’s functions file or add via plugin:

// Enable oEmbed on Custom Fields
add_filter('get_post_metadata', array($GLOBALS['wp_embed'], 'autoembed'), 9);

You may notice a pattern with these last two snippets, and as you may suspect the same basic technique can be applied to other areas of WordPress to enable oEmbed functionality.

Good times.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress