Remove Autoplay From Embedded Videos
Strips autoplay settings from YouTube and Vimeo embeds in posts, so videos only start when the visitor presses play.
Opens WPIDE on
Code
$wpide_strip_autoplay = function ( $html ) {
if ( false === stripos( $html, 'autoplay' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $html;
}
$tags = new WP_HTML_Tag_Processor( $html );
while ( $tags->next_tag( 'iframe' ) ) {
$src = (string) $tags->get_attribute( 'src' );
if ( preg_match( '#(youtube\.com|youtube-nocookie\.com|player\.vimeo\.com)#i', $src ) ) {
$tags->set_attribute( 'src', remove_query_arg( array( 'autoplay', 'mute', 'muted', 'background' ), $src ) );
}
$allow = (string) $tags->get_attribute( 'allow' );
if ( $allow ) {
$tags->set_attribute( 'allow', trim( preg_replace( '/\s*autoplay;?/i', '', $allow ) ) );
}
}
return $tags->get_updated_html();
};
add_filter( 'embed_oembed_html', $wpide_strip_autoplay, 20 );
add_filter( 'the_content', $wpide_strip_autoplay, 20 );
Notes
Background videos added as Cover blocks are not embeds and are not changed by this snippet.
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.