2

I'm going through some legacy code and adding i18n functions throughout when I stumbled on a localisation snippet I found inside a pre_get_document_title function: (simplified)

$title = 'Hello World';
__( $title, 'my_text_domain' );

This returns the correct, translated string. It was recently pointed out to me however, that this isn't valid syntax as localisation functions should only receive a string; not a variable, nor a function return value. The recommended (and correct) syntax, as seen in numerous themes:

sprintf( __( '%s', 'my_text_domain' ), $title );

Having made this change, I find that all my titles are now still in English. i.e. nothing gets translated. All the language files are still there, all I did was modify the __() calls.

Is there something I missed?

4
  • I don't see any issues with the above code. There is smething else going on. Did you generate the language file again after you changed the __() calls? Commented Sep 26, 2016 at 17:22
  • My guess is that if you generate the .pot, .md files again, it would be fixed. Commented Sep 26, 2016 at 17:25
  • The site's been up with several locales for some time with no translation issues until this cropped up. Should I try recompiling all the .mo files again? Commented Sep 26, 2016 at 17:51
  • I suppose it may fix it, just try it if you can. Commented Sep 26, 2016 at 17:52

1 Answer 1

2

The order of the functions being called is wrong.

With this code:

sprintf( __( '%s', 'my_text_domain' ), $title );
  • You are trying to translate the string '%s' in the domain 'my_text_domain'.
  • you are then replacing the translated string for '%s' (which is '%s'), by the content of the variable $title.
  • Therefore your code is similar to sprintf( '%s', $title);

What you should do:

__( sprintf( '%s', $title ), 'my_text_domain' );
  • sprintf() will return your title
  • __() will translate the returned title

By the way, if you plan to use the title of the post only, you probably don't need to use sprintf() but instead:

__( $title, 'my_text_domain );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.