Stop Audio and Unmuted Videos From Autoplaying
Removes the autoplay setting from audio players and from videos that are not muted in your content, so sound never starts without the visitor choosing to play it.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, 'autoplay' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $content;
}
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag() ) {
$tag = $tags->get_tag();
if ( ( 'AUDIO' === $tag || ( 'VIDEO' === $tag && null === $tags->get_attribute( 'muted' ) ) ) && null !== $tags->get_attribute( 'autoplay' ) ) {
$tags->remove_attribute( 'autoplay' );
$tags->set_attribute( 'controls', true );
}
}
return $tags->get_updated_html();
}, 20 );
Notes
Muted background videos keep autoplaying; use the reduced-motion video snippet if those should stop too.
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.