Main menu

Filter the JSON translation file used for a text domain

This filter allows plugin authors to dictate a single JSON file to hold all script translations for a text domain. The initial value passed through this filter is empty, because the default behaviour is to compile a JSON file for every dependent JavaScript file.

Loco Translate handles this logic at compile-time only. Authors must additionally filter on load_script_translation_file to ensure the same functionality is honoured by WordPress at runtime.

The following example returns a .json file with the same name as the .po file from which the JSON is being compiled:

/**
 * Take PO file name for all JSON files in my-domain
 */
function compile_single_json_for_my_domain( $jsonPath, $poPath ){
    $info = pathinfo($poPath);
    if( 'my-domain' === substr($info['filename'],0,9) ){
        $path = $info['dirname'].'/'.$info['filename'].'.json';
    }
    return $path;
}

/**
 * Strip MD5 suffix from all JSON files in my-domain
 */
function load_single_json_for_my_domain( $file, $handle, $domain ){
    if( 'my-domain' === $domain && is_string($file) ){
        $file = substr($file,-38).'.json';
    }
    return $file;
}

add_filter('loco_compile_single_json','compile_single_json_for_my_domain',999,2);
add_filter('load_script_translation_file','json_for_my_domain',999,3);

This example assumes that the load_script_translation_file filter initially receives a hashed file name generated by WordPress, then simply strips off the MD5 hash.

See also

Last updated by