Last active
January 14, 2025 08:14
-
-
Save audrasjb/f4b6c291f66ac4d25a4bbe06ec788639 to your computer and use it in GitHub Desktop.
Filters blocks to automatically add aria-label to links that open in a new tab.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Filters blocks to automatically add aria-label to links that open in a new tab. | |
* | |
* @param string $block_content The block content. | |
* @param array $block The full block, including name and attributes. | |
*/ | |
function who_accessible_external_links( $block_content, $block ) { | |
$blocklist = array( | |
'core/button', | |
'core/paragraph', | |
'core/list', | |
'core/heading', | |
'core/quote', | |
'core/pullquote', | |
'core/table', | |
'core/file', | |
'core/image', | |
'core/gallery', | |
); | |
/** | |
* Filters blocks that have to be processed. | |
* | |
* @param array $blocklist An array of block names. | |
*/ | |
$blocklist = apply_filters( 'who_accessible_external_links_blocklist', $blocklist ); | |
if ( in_array( $block['blockName'], $blocklist ) ) { | |
$processor = new WP_HTML_Tag_Processor( $block_content ); | |
while ( $processor->next_tag( 'a' ) ) { | |
if ( '_blank' === $processor->get_attribute( 'target' ) ) { | |
$processor->set_attribute( 'aria-label', esc_attr__( 'opens in a new tab', 'accessible-external-links' ) ); | |
$processor->set_attribute( 'rel', 'external' ); | |
} | |
} | |
return $processor->get_updated_html(); | |
} | |
return $block_content; | |
} | |
add_filter( 'render_block', 'who_accessible_external_links', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment