First of all, let me try to clarify that your stack here is splitted in 3:
- Back-end (Wordpress/PHP)
- Front-end (Html, JS, CSS)
- Algolia (External API)
So what happens is:
- Your back-end prints a html page requested by the client's browser.
- In this page, a javascript makes a query to Algolia's API.
- The same javascript updates the page content depending on Algolia's response without reloading the page.
This means that the back-end job here stops at step 1 and you can't use php on steps 2 and 3.
Ok, now there are a couple of ways to translate the dynamic content coming from algolia:
Solution 1
The best solution
If you can, you may use a different algolia index for each language when you init algolia's instantsearch.
For exemple:
...
const search = instantsearch({
appId: 'YOUR_API_ID',
apiKey: 'YOUR_API_KEY',
indexName: 'movies_en' // or 'movies__fr' or 'movies__es'
// Here you could make the indexName dynamic using a variable, like this:
// indexName: 'movies_' + currentLanguage
});
...
Now you just need to print the right index for the right language.
Solution 2
More complicated, less maitanable solution
You can print a translation JSON somewhere on your page (with PHP if you wan't)
<script>
window.algoliaTranslations: {
"Guardians of the Galaxy": {
"fr": "Gardiens de la Galaxie",
"es": "Guardianes de la Galaxia",
}
}
</script>
and translate the label on the fly
const currentLanguage = 'es'
search.addWidget(
instantsearch.widgets.hits({
container: '#hits',
hitsPerPage: 12,
templates: {
item: `
<label class="ais-RefinementList-label">
<input type="checkbox" class="ais-RefinementList-checkbox" value="{{label}}">
<span class="ais-RefinementList-labelText">{{label}}</span>
<span class="ais-RefinementList-count">{{count}}</span>
</label>
`,
},
transformData: hit => {
hit.label = window.algoliaTranslations[hit.label][currentLanguage]
return hit;
},
})
);
In solution 1 most of the work is done in Algolia while in solution 2 this work is done in php/javascript
Hope this will help.