Home > Blog > Translation > Translate ajax strings in WordPress

Translate ajax strings in WordPress

By Cristian
Last Updated: July 29th, 2022

Loading content with AJAX is used by a lot of WordPress themes and plugins (like WooCommerce) 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 can see ajax strings in:

  • checkout pages
  • multi-step forms
  • widgets
  • 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.

Translate AJAX Strings in WordPress

The trick to translating 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 frontend JavaScript is using to output or what it’s doing with the AJAX response.

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

Gettext fields in AJAX request

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

So there’s a good chance that all 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 fewer 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 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 whole.

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 to-do list and we’re really happy with how it turned out. So start translating those AJAX-driven interfaces today.

Do you still have questions about translating AJAX string in WordPress? Let us know in the comments!

If you found this post helpful, please check out our YouTube channel, where we constantly upload short & easy-to-follow video tutorials. You can also follow us on Facebook and Twitter to be the first to know each time we post.