Skip to content

Instantly share code, notes, and snippets.

@jlengstorf
Created October 8, 2014 20:28
Show Gist options
  • Save jlengstorf/ce2470df87fd9a892f68 to your computer and use it in GitHub Desktop.
Save jlengstorf/ce2470df87fd9a892f68 to your computer and use it in GitHub Desktop.
Adds responsive embedding to WordPress oEmbed content.

Responsive Embeds in WordPress

This snippet filters oEmbed output in WordPress (the_content()) to force responsive embeds.

Usage

To use, add the contents of responseive_embeds.less to your site's stylesheet (if you're not using LESS, don't forget to move the iframe,object,embed rule outside of .embed-container and change it to .embed-container iframe,.embed-container object,.embed-container embed).

Then add the responsive_embed() function to your theme's functions.php and insert the add_filter() call in your theme's setup function.

NOTE: If your theme is not a child theme, this can be placed directly below responsive_embed(), outside of any function.

<?php
function setup_theme( ) {
// Theme setup code...
// Filters the oEmbed process to run the responsive_embed() function
add_filter('embed_oembed_html', 'responsive_embed', 10, 3);
}
add_action('after_setup_theme', 'setup_theme');
/**
* Adds a responsive embed wrapper around oEmbed content
* @param string $html The oEmbed markup
* @param string $url The URL being embedded
* @param array $attr An array of attributes
* @return string Updated embed markup
*/
function responsive_embed($html, $url, $attr) {
return $html!=='' ? '<div class="embed-container">'.$html.'</div>' : '';
}
.embed-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
max-width: 100%;
height: auto;
iframe, object, embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
@em-piguet
Copy link

/**
 * Enable responsive embed support.
 * @link https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/#responsive-embedded-content
 */
add_theme_support('responsive-embeds');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment