Home / Archive / Accessibility Improvement
Duplicate Snippet

Embed Snippet on Your Site

Accessibility Improvement

GOALS:
Match ARIA attributes to valid roles (e.g., avoid aria-expanded on elements without expandable roles).

Ensure all or tags have a title attribute.

Ensure all tags (links) have discernible names (e.g., not just or icons without labels).

Code Preview
php
<?php
// 1. Ensure ARIA attributes match proper roles
function nexsouk_fix_aria_roles($content) {
    // Simplistic approach: strip aria-* from elements without proper roles
    // Better: adjust based on your theme/structure with context
    $valid_roles = array(
        'button' => ['aria-pressed', 'aria-expanded'],
        'navigation' => ['aria-label', 'aria-labelledby'],
        'dialog' => ['aria-modal', 'aria-labelledby'],
        'tabpanel' => ['aria-hidden', 'aria-labelledby'],
        'checkbox' => ['aria-checked'],
        'link' => ['aria-current'],
        // add more as needed
    );
    foreach ($valid_roles as $role => $valid_attrs) {
        $pattern = '/<([a-z0-9]+)([^>]*role=["\']' . preg_quote($role, '/') . '["\'][^>]*)>/i';
        $content = preg_replace_callback($pattern, function ($matches) use ($valid_attrs) {
            $tag = $matches[1];
            $attrs = $matches[2];
            // Remove invalid aria-* attributes
            $attrs = preg_replace_callback('/aria-([a-zA-Z0-9_-]+)=["\'][^"\']*["\']/', function ($a) use ($valid_attrs) {
                return in_array('aria-' . $a[1], $valid_attrs) ? $a[0] : '';
            }, $attrs);
            return "<$tag$attrs>";
        }, $content);
    }
    return $content;
}
add_filter('the_content', 'nexsouk_fix_aria_roles');
// 2. Ensure iframes have a title attribute
function nexsouk_add_title_to_iframes($content) {
    return preg_replace_callback('/<iframe([^>]*)>/i', function ($matches) {
        $attrs = $matches[1];
        // Check if title is already present
        if (stripos($attrs, 'title=') === false) {
            $title = 'Embedded content from external site';
            return '<iframe title="' . esc_attr($title) . '"' . $attrs . '>';
        }
        return $matches[0];
    }, $content);
}
add_filter('the_content', 'nexsouk_add_title_to_iframes');
// 3. Ensure links have discernible names
function nexsouk_add_accessible_link_text($content) {
    return preg_replace_callback('/<a\s([^>]*href=["\'][^"\']+["\'][^>]*)>(\s*)<\/a>/i', function ($matches) {
        // If anchor has no text, add visually hidden fallback
        $new_content = $matches[0];
        $placeholder = 'Link'; // You could dynamically generate based on URL context
        if (trim($matches[2]) === '') {
            $new_content = '<a ' . $matches[1] . '><span class="sr-only">' . esc_html($placeholder) . '</span></a>';
        }
        return $new_content;
    }, $content);
}
add_filter('the_content', 'nexsouk_add_accessible_link_text');

Comments

Add a Comment