[Resolved] How to localize author name when using GenerateBlocks

Home Forums Support [Resolved] How to localize author name when using GenerateBlocks

Home Forums Support How to localize author name when using GenerateBlocks

  • This topic has 3 replies, 2 voices, and was last updated 2 years ago by David.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2161432
    Oleksiy

    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

    #2161837
    David
    Staff
    Customer Support

    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.

    #2162047
    Oleksiy

    Awesome! Thanks a lot, David!

    #2162051
    David
    Staff
    Customer Support

    Glad to be of help!

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.