Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.