Hi @yankiara,
Thanks for the kind words and the thoughtful suggestions.
As far as I know, using the <title> element inside an SVG is currently the better option from an accessibility standpoint. That said, I understand the drawback you mentioned with the tooltip, and I’ve noted your idea. I’ll consider adding this as a feature in the future.
For now, if you don’t want the tooltip and prefer to use aria-label instead, you can use the custom code below as a workaround:
add_filter(
'render_block_boldblocks/svg-block',
function ( $block_content, $block ) {
$attrs = $block['attrs'] ?? [];
$has_link = ( $attrs['linkUrl'] ?? '' ) || ( $attrs['linkToPost'] ?? false );
$title = $attrs['title'] ?? '';
$description = $attrs['description'] ?? '';
if ( ! $has_link || $title || ! $description ) {
return $block_content;
}
$block_reader = new \WP_HTML_Tag_Processor( $block_content );
if ( $block_reader->next_tag( 'a' ) ) {
$block_reader->set_attribute( 'aria-label', esc_attr( $description ) );
if ( $block_reader->next_tag( 'svg' ) ) {
$block_reader->set_attribute( 'aria-hidden', 'true' );
$block_content = $block_reader->get_updated_html();
}
}
return $block_content;
},
20,
2
);
To make this code work, you need to leave the title field empty to remove the tooltip and fill in the description field. That description will be used as the aria-label for the link.
Best, Phi.
Thread Starter
Yan
(@yankiara)
Hi, and thanks for your fast answer!
The code snippet doesn’t work as is for me, because there are no linkUrl or linkToPost attributes in the block (I checked with var_dump()). So I tried to comment out the return line and it works OK 🙂
Am I right to say that the $block_reader->next_tag( 'a' ) test does the job, anyway? Since the link shouldn’t be rendered if not set in the block?
Glad I could learn some basics about the HTML API, by the way!
@yankiara You’re right. We don’t actually need to check whether the block has a link. The next_tag( ‘a’ ) check already covers that.
What is still worth checking is whether a description exists. If there’s no description, there’s nothing to use for the aria-label, so we can skip parsing the HTML entirely.
Thanks as well for pointing this out, and I’m glad the snippet helped you get a feel for the HTML API. That HMTL API is really powerful and easy to work with.
Happy holidays!
Thread Starter
Yan
(@yankiara)
Yes I’m keeping the description test, this is perfect like this.
Happy holidays too and wish you the best!