Responsive Video Embeds From ACF oEmbed Fields
Wraps the output of ACF oEmbed fields in a 16:9 container and adds lazy loading, so embedded videos scale to the screen instead of overflowing on phones.
Opens WPIDE on
Code
// Aspect ratio of the container.
$wpide_acf_embed_ratio = '16 / 9';
add_filter( 'acf/format_value/type=oembed', function ( $value ) use ( $wpide_acf_embed_ratio ) {
if ( ! is_string( $value ) || false === strpos( $value, '<iframe' ) ) {
return $value;
}
$value = preg_replace( '/<iframe(?![^>]*\sloading=)/', '<iframe loading="lazy"', $value );
$value = preg_replace( '/\s(width|height)="\d+"/', '', $value );
return '<div class="acf-embed" style="aspect-ratio:' . esc_attr( $wpide_acf_embed_ratio ) . ';width:100%">' . str_replace( '<iframe', '<iframe style="width:100%;height:100%;border:0"', $value ) . '</div>';
} );
Notes
Change the aspect ratio for vertical or square videos.
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.