Responsive Video Embeds for Classic Themes
Makes YouTube, Vimeo and other embedded videos scale to the width of the content on phones and tablets, for older themes that leave them at a fixed size.
Opens WPIDE on
Code
add_filter( 'embed_oembed_html', function ( $html ) {
if ( current_theme_supports( 'responsive-embeds' ) || wp_is_block_theme() || false === strpos( $html, '<iframe' ) || false !== strpos( $html, 'wpide-responsive-embed' ) ) {
return $html;
}
$width = preg_match( '/\swidth=["\']?(\d+)/i', $html, $w ) ? (int) $w[1] : 16;
$height = preg_match( '/\sheight=["\']?(\d+)/i', $html, $h ) ? (int) $h[1] : 9;
if ( ! $width || ! $height ) {
$width = 16;
$height = 9;
}
return '<div class="wpide-responsive-embed" style="position:relative;width:100%;aspect-ratio:' . $width . '/' . $height . ';">' . $html . '</div>';
}, 20 );
add_action( 'wp_head', function () {
echo '<style>.wpide-responsive-embed iframe{position:absolute;inset:0;width:100%;height:100%;}</style>' . "\n";
} );
Notes
Block themes and themes that already declare responsive embeds are skipped automatically.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.