Accessibility PHP Beginner

Stop Videos Autoplaying

Remove autoplay from Video and Cover blocks so videos only play when visitors press play, and add controls where they're missing.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 17 lines
add_filter( 'render_block', function ( string $html, array $block ): string {
	if ( ! in_array( $block['blockName'] ?? '', [ 'core/video', 'core/cover' ], true ) || ! str_contains( $html, '<video' ) ) {
		return $html;
	}

	$tags = new WP_HTML_Tag_Processor( $html );
	while ( $tags->next_tag( 'video' ) ) {
		$tags->remove_attribute( 'autoplay' );

		// Background videos in Cover blocks need a way to start them.
		if ( null === $tags->get_attribute( 'controls' ) ) {
			$tags->set_attribute( 'controls', true );
		}
	}

	return $tags->get_updated_html();
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Video that starts on its own is distracting for many people and can interfere with screen readers. WCAG asks that anything moving for more than five seconds can be paused. This snippet makes every video wait for the visitor.

How it works

render_block filters each block’s HTML as the page is built. For Video and Cover blocks, WP_HTML_Tag_Processor finds the <video> tag, removes autoplay, and adds controls if there were none, so the video can be started.

Things to watch

  • Cover blocks with a background video will show a still frame with player controls instead of moving video. That’s the intended trade-off.
  • YouTube and Vimeo embeds aren’t affected; they don’t autoplay unless set in their URL.

How to test it

View a page with a Video block set to autoplay. It should no longer start on its own, and should show player controls.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only