Accessibility PHP Intermediate

Make Wide Tables Scrollable and Labelled

Let wide Table blocks scroll sideways on phones, and make the scroll area reachable and announced for keyboard and screen reader users.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 21 lines
add_filter( 'render_block_core/table', function ( string $html, array $block ): string {
	$tags = new WP_HTML_Tag_Processor( $html );

	if ( $tags->next_tag( 'figure' ) ) {
		$caption = '';
		if ( preg_match( '#<figcaption[^>]*>(.*?)</figcaption>#is', $html, $m ) ) {
			$caption = trim( wp_strip_all_tags( $m[1] ) );
		}

		$tags->set_attribute( 'role', 'region' );
		$tags->set_attribute( 'tabindex', '0' );
		$tags->set_attribute( 'aria-label', '' !== $caption ? $caption : 'Table' );
		$tags->add_class( 'nahnu-scroll-table' );
	}

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

add_action( 'wp_head', function (): void {
	echo '<style>.nahnu-scroll-table{overflow-x:auto}.nahnu-scroll-table table{min-width:32rem}.nahnu-scroll-table:focus-visible{outline:3px solid #6F58CA;outline-offset:2px}</style>';
} );

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.

Wide tables either squash into unreadable columns on phones or break the layout. Letting them scroll sideways fixes that, but a scrolling box must be reachable with the keyboard and have a name, or some users can’t read the hidden columns.

How it works

The render_block_core/table filter runs for every Table block. WP_HTML_Tag_Processor adds role="region", tabindex="0" so keyboard users can focus it and scroll with the arrow keys, and an aria-label taken from the table’s caption.

A little CSS lets the box scroll sideways, keeps the table at least 32rem wide so columns stay readable, and shows a focus outline.

Things to watch

  • Add captions to your tables. They become the label screen readers announce, instead of the generic “Table”.
  • Only Table blocks are changed, not tables from shortcodes or the classic editor.

How to test it

View a post with a wide Table block on a phone. It should scroll sideways. On desktop, Tab to it and use the arrow keys to scroll.

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