The load_script_translations WordPress PHP Filter allows you to modify script translations for a specific file, script handle, and text domain.
Usage
add_filter('load_script_translations', 'your_custom_function', 10, 4);
function your_custom_function($translations, $file, $handle, $domain) {
// your custom code here
return $translations;
}
Parameters
- $translations (string): JSON-encoded translation data.
- $file (string): Path to the translation file that was loaded.
- $handle (string): Name of the script to register a translation domain to.
- $domain (string): The text domain.
More information
See WordPress Developer Resources: load_script_translations
Examples
Adding Custom Translations
Add custom translations to your script.
add_filter('load_script_translations', 'my_custom_translations', 10, 4);
function my_custom_translations($translations, $file, $handle, $domain) {
if ('my-script' === $handle) {
$custom_translations = array(
'hello' => __('Hello', 'my-domain'),
'world' => __('World', 'my-domain'),
);
$translations = json_encode($custom_translations);
}
return $translations;
}
Changing Text Domain
Change the text domain for a specific script.
add_filter('load_script_translations', 'change_text_domain', 10, 4);
function change_text_domain($translations, $file, $handle, $domain) {
if ('my-script' === $handle) {
$domain = 'new-domain';
}
return $translations;
}
Removing Translations
Remove translations for a specific script.
add_filter('load_script_translations', 'remove_translations', 10, 4);
function remove_translations($translations, $file, $handle, $domain) {
if ('my-script' === $handle) {
$translations = '';
}
return $translations;
}
Modifying Existing Translations
Modify existing translations for a specific script.
add_filter('load_script_translations', 'modify_existing_translations', 10, 4);
function modify_existing_translations($translations, $file, $handle, $domain) {
if ('my-script' === $handle) {
$translations_array = json_decode($translations, true);
$translations_array['hello'] = __('Hi', 'my-domain');
$translations = json_encode($translations_array);
}
return $translations;
}
Loading Translations from Custom File
Load translations from a custom file for a specific script.
add_filter('load_script_translations', 'load_custom_file_translations', 10, 4);
function load_custom_file_translations($translations, $file, $handle, $domain) {
if ('my-script' === $handle) {
$custom_file = '/path/to/your/custom/translations-file.json';
$translations = file_get_contents($custom_file);
}
return $translations;
}