Site logo

Archived topic

Add a dynamic Aria Label when using a Dynamic Link for the Container

5 replies · Started by Dan on October 10, 2022

Viewing posts 1–6 of 6

Hey, is it possible to add dynamic aria labels when using the Dynamic Link feature for the whole container? In my use case, I am building a template for the blog archive; I have a parent Container holding the featured image, meta, etc. I want to use this parent Container as the link to the post and include an Aria Label of the post title. I've tried to use a shortcode in the field but it gets stripped. See the below screenshot for additional context.

Screenshot of dynamic Aria Label

Hi Dan,

Do you mean you want to add the post title to the aria-label?
Let me know!

Hi @ying, yes that's correct. I'm looking to set the post tile as the Aria Label.

We can try these steps:

1. Add an additional CSS class to the container block, eg. add-title-aria-label.
Adding CSS class(es): https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/

2. Add title as the aria label:
https://www.screencast.com/t/JFuclCwcfmv

3. Add this PHP snippet to replace the static title text with dynamic post title:

function add_title_aria_label( $block_content, $block ) {
	if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'add-title-aria-label' ) !== false ) {
		    $post_title = get_the_title(get_the_ID());
			$my_search='aria-label="title';
			$my_replace='aria-label="'.$post_title;
			$new_content = str_replace($my_search, $my_replace, $block_content);
			return $new_content;
	}
    return $block_content;
}
 
add_filter( 'render_block', 'add_title_aria_label', 10, 2 );

Adding PHP: https://docs.generatepress.com/article/adding-php/

Nice solution, Ying. Thank you :)

You are welcome :)

This archived topic is closed to new replies.