Site logo

Archived topic

How to localize author name when using GenerateBlocks

3 replies · Started by Oleksiy on March 20, 2022

Viewing posts 1–4 of 4

Hi guys,

Before GenerateBlocks was introduced I've used the following code in functions.php to localize author name for different languages (unfortunately Polylang or Loco Translate plugins can't help here):

add_filter( 'generate_post_author_output', 'tu_add_author_gravatar' );
function tu_add_author_gravatar() {
	$author_name = 'Author name in English';
    if (get_locale() == 'uk') {		
        $author_name = 'Author name in Ukrainian';
    }		
	printf( ' <span class="byline">%1$s</span>',
		sprintf( '<span class="author vcard" itemtype="http://schema.org/Person" itemscope="itemscope" itemprop="author">%1$s %5$s <span class="fn n author-name" itemprop="name">%4$s</span></span>',
			__( '','generatepress'),
			esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
			esc_attr( sprintf( __( 'View all posts by %s', 'generatepress' ), $author_name ) ),
			$author_name,
			get_avatar( get_the_author_meta( 'ID' ) )
		)
	);
}

It was working fine.

Recently I've created an Author Block for a new website based on your video tutorial - https://www.youtube.com/watch?v=HMhUo91RjsE
And the code above is not working for this block. But if I switch on the old version of displaying author name (without using GenerateBlocks), it works.

Is there a solution to localize author name using GenerateBlocks?

Thanks

Hi there,

there is a filter for the blocks.

First select the block that is displaying the Author, and in Advanced > Additional CSS Class(es) enter a custom class eg. author-name

Now add this snippet:

add_filter( 'generate_dynamic_element_text', function( $text, $block ) {
    if ( ! empty( $block['attrs']['className'] ) && 'author-name' === $block['attrs']['className'] && get_locale() == 'uk') ) {
        $text = 'Author name in Ukrainian';
    }

    return $text;
}, 10, 2 );

This will change the text of the block if the get_locale() == 'uk' - and therefore assumes that the default output is already displayed in English.

Awesome! Thanks a lot, David!

Glad to be of help!

This archived topic is closed to new replies.