I display messages using code snippets but how can I use the right language?

Question

I use code snippets to display messages in my site, for example, next to the “Post Comment” button I display the text “Your message will only be visible after manual moderation”. I use this code for that:

add_action( 'comment_form', 'wpse_93795_comment_form' );
function wpse_93795_comment_form( $post_id ) {
    printf( '<span class="submit-comment-note">%s</span>',
      __( 'Your message will only be visible after manual moderation', 'your_text_domain' ) );
}

My question is: Can have a “switch” here to write a text depending on the language?
For example, if the language set in the site is English I want to display ‘Your message will only be visible after manual moderation’
But if language is Spanish I want to display “Su mensaje sólo será visible tras ser manualmente revisado”

I use Polylang for having different languages in the site.
Thanks

in progress 0
Ton 2 weeks 2021-09-15T14:33:19-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-09-19T04:02:27-05:00

    You already have it in the code:

    __( 'Your message will only be visible after manual moderation', 'your_text_domain' )
    

    __ is a translation function and part of the static string translation system in WordPress core. Polylang might allow you to translate dynamic content, but __() and its friends are for static strings. These use the standardised gettext format of .po and .pot/.mo files, with each file listing out all the strings and their counterpart in another language. Each language has its own file.

    This system is great for user interfaces, and theme/plugin strings that don’t change. Do not try to use it with variables and dynamic data though.

    Normally you would need to change the language of your site to switch these to another language for everybody, but since you have Polylang you can use its built in language selection tools to switch between languages.

    See the internationalisation section of the theme handbook.

    E.g. if you had this:

    <h1>A big title</h1>
    

    Then it would be best practice to make this translatable e.g.

    <h1><?php echo __( 'A big title', 'text-domain-goes-here' ); ?></h1>
    

    Notice each call specifies a text domain which lets it know to use the string from your theme/plugin.

Leave an answer

Browse
Browse