Loading content with AJAX is used by a lot of WordPress 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 posts and pages.
In WordPress, you’ll see ajax strings in:
- checkout pages
- multi-step forms
- infinite scrolls
- booking forms
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 have actually implemented this.
The trick to translate AJAX strings in WordPress is using the same functionality for AJAX loaded content as for a normal page load.
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.
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 change 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.
This pretty much sums it up. 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!