Add Scope to Table Header Cells
Adds scope="col" or scope="row" to table header cells in post content that lack it, so screen readers can tie each data cell to its header.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, '<th' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $content;
}
$tags = new WP_HTML_Tag_Processor( $content );
$row = 0;
$in_thead = false;
while ( $tags->next_tag( array( 'tag_closers' => 'visit' ) ) ) {
$tag = $tags->get_tag();
if ( 'THEAD' === $tag ) {
$in_thead = ! $tags->is_tag_closer();
} elseif ( 'TABLE' === $tag && ! $tags->is_tag_closer() ) {
$row = 0;
} elseif ( 'TR' === $tag && ! $tags->is_tag_closer() ) {
$row++;
} elseif ( 'TH' === $tag && ! $tags->is_tag_closer() && null === $tags->get_attribute( 'scope' ) ) {
$tags->set_attribute( 'scope', ( $in_thead || 1 === $row ) ? 'col' : 'row' );
}
}
return $tags->get_updated_html();
}, 20 );
Notes
Header cells in the first row get scope="col"; header cells elsewhere get scope="row".
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.