# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Accessibility](https://wpide.com/library/category/accessibility/)
- Tags: tables, screen-reader, content
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/a11y-table-header-scope/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add Scope to Table Header Cells" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
