I’m stuck with a Campaign Monitor plugin that isn’t WPML-ready. I need to translate some error messages in the JavaScript file. Here’s a snippet from the app.js file:
function validateSignupForm() {
// ... some code ...
if (emailInput.length < 1) {
errorText = 'Please enter a valid email address';
errors.push('Email is required');
highlightField('#signupEmailField');
} else if (!isValidEmail(emailInput)) {
errors.push('Email format is incorrect');
highlightField('#signupEmailField');
}
// ... more code ...
}
I’ve seen examples of using wp_localize_script() for translations, but I’m confused about the ‘handle’ and ‘object_name’ parameters. Is there an easier way to translate these error messages?
Another approach you might consider is using a JavaScript-based translation library like i18next. It’s lightweight and can be easily integrated into your existing setup.
Here’s how you could implement it:
Include i18next in your project.
Create a JSON file for each language with your translations.
Initialize i18next in your JavaScript code.
Use the t() function to translate your strings.
Your validateSignupForm function could then look like this:
function validateSignupForm() {
if (emailInput.length < 1) {
errorText = i18next.t('emailRequired');
errors.push(i18next.t('emailRequiredError'));
highlightField('#signupEmailField');
} else if (!isValidEmail(emailInput)) {
errors.push(i18next.t('emailInvalidError'));
highlightField('#signupEmailField');
}
}
This method gives you more flexibility and keeps your translations separate from your code, making maintenance easier in the long run.
I’ve dealt with a similar situation before, and I can share what worked for me. Instead of messing with wp_localize_script(), which can be tricky, I found a simpler approach.
What I did was create a small PHP file that defines these error messages as JavaScript variables. Then, I enqueued this file to load before the main app.js. Here’s how it looked:
function translate_error_messages() {
?>
<script>
var errorMessages = {
emailRequired: '<?php _e('Please enter a valid email address', 'your-text-domain'); ?>',
emailInvalid: '<?php _e('Email format is incorrect', 'your-text-domain'); ?>'
};
</script>
<?php
}
add_action('wp_head', 'translate_error_messages');
Then in your app.js, you can use these variables:
if (emailInput.length < 1) {
errorText = errorMessages.emailRequired;
// rest of your code
} else if (!isValidEmail(emailInput)) {
errors.push(errorMessages.emailInvalid);
// rest of your code
}
This way, WordPress handles the translations, and you don’t need to modify the plugin files directly. It’s been a reliable solution for me across different projects.