Localizing strings that come from outside of plugin?

Plugin queries remote API and under certain circumstances (mostly errors) displays textual messages from API responses. All messages in API responses are in English, but since they are more or less integrated in plugin it would make sense to make them localized and display-able in different language to match plugin’s interface.

Theoretical question – should such messages be localized at all or are they out of scope for localization?

Coding question – how do you even localize such and retain compatibility with related tools? Does something like __( $message ); even make sense?

In the past I used Codestyling Localization which relies on scanning plugin’s source to extract strings… But there is nothing to extract since strings are not contained in plugin’s body.

2 Answers
2

Should such messages be localized at all or are they out of scope for localization?

Yes, they should be localized … but don’t depend on the text returned by the API.

Does something like __( $message ); even make sense?

Not really. First of all, you’re not providing a text domain for the string to use in localization. It should really be __( $message, 'my-text-domain' );. Even then, if you don’t have a static list of values for $message, localaization is a moot point.

What You Can Do Instead

The Robustness Principle is a great thing to keep in mind whenever you integrate content from an external API. You can never fully trust what the API gives you … the original owners might change things around without notifying you, or their system might break and provide erroneous information. So you should always:

Be conservative in what you send; be liberal in what you accept.

If you already know what content the API will return (i.e. a static list of strings), put that in your plug-in. Then use a sanitation method to map what the API returned to your localized strings.

For example:

$map = array( 
    'This is one return' => __( 'This is one return', 'my-text-domain' ),
    'This is another' => __( 'This is another', 'my-text-domain' )
);

sanitize_api_feedback( $api_sent ) {
    return $map[$api_sent];
}

In this way, you never actually use the raw output of the external API but always run it through your own filter. You have complete control over the text strings used and can run them through the standard localization filters as well.

If the API Return is Free-form

If you don’t have a list of static strings returned by the API, this won’t work. Then again, if the API returns free-form content you should either:

  1. Leave localization up to the API itself (if possible)
  2. Provide you end user with some other translation service … maybe Google Translate

There’s no way your plug-in can be responsible for translating free-form strings on the fly. But a static list of easily-expected error messages? That’s definitely something you can, and should, do.

Leave a Comment