Translate ajax strings in WordPress

Loading content with AJAX is used by a lot of themes and plugins to show content and extend functionality without reloading the page. For a fully multilingual website, we need to translate AJAX strings in WordPress, as well as standard strings from your post and page.

In WordPress, you’ll see this in:

  • checkout pages
  • multi-step forms
  • widgets
  • infinite scrolls
  • booking forms
  • etc

In TranslatePress, we’re detecting AJAX strings and you can translate them just like a normal string. But that’s not where the magic happens. So let’s get a closer look at how we’ve actually implemented this.

Translate AJAX Strings in WordPress

The trick to translate AJAX strings in WordPress is using the same functionality for AJAX loaded content as for a normal page load.

This means we’re not making any assumptions as to what the front-end javascript is using to output or what it’s doing with the AJAX response.

We’re just translating the content as long as it’s HTML.

Gettext fields in ajax request

Gettext fields already come wrapped in translation tags from the gettext filter. As long as the locale is setup correctly in WordPress, we’re detecting all the strings loaded in that ajax request.

So it’s a good chance those strings will appear already translated from .po files for a lot of plugins.

Conclusions

By translating AJAX requests on the php side of things, we didn’t have to have two parsers (both php and js). So more code reuse, less complexity and hopefully less bugs.

We still have a JS dom chang listener that tracks down text changes that are not AJAX requests, but that’s a discussion for another time. It’s doing things a bit differently compared to the php parser so it’s while we do have to manage extra code that conceptually does the same thing, it has a lot less impact on the entire experience as a hole.

So this is it. TranslatePress was designed from the get go to allow you to translate everything from the same simple interface. AJAX translation was a big item on our todo list and we’re really happy how it turned out. So start translating those AJAX driven interfaces today.

Keep in touch!

We'll only notify you of new articles, special promotions and updates. No spam!

Leave a Reply

Your email address will not be published. Required fields are marked *