Main menu

loco_compile_script_reference

Filter whether JSON translations should be compiled for a given script reference

Loco Translate avoids generating JSON files for script files that don't exist. This can happen if a build system has references to .js source files which are not publicly distributed and therefore never loaded at runtime.

WordPress's load_script_textdomain_relative_path filter allows authors to transform such references into published (minified) paths, but Loco Translate's JSON compiler will still check that the resultant script file exists.

Available since v2.6.0, Loco Translate's loco_compile_script_reference filter allows authors to override this behaviour and dictate whether a given script path should be used or not.

The following example simply tells Loco Translate that all file references in a text domain are valid and must always have their JSON translations compiled:

/**
 * @param bool whether the script file exists on disk
 * @param string relative path to script file, either .js or .min.js
 * @param string script text domain for theme or plugin
 * @return bool whether to compile a JSON file for this script
 */
function compile_script_reference_for_my_domain( $bool $relative $domain ){
    if( 'my-plugin' === $domain  ){
        return true;
    }
    return $bool;
}

add_filter('loco_compile_script_reference','compile_script_reference_for_my_domain',999,3);

Notes:

  • This filter does not alter the relative path, because $relative has already been filtered. All it does is say whether the file should be treated as if it exists.
  • It doesn't matter whether the $relative path ends with .js or .min.js as the JSON file name will not be affected by this.

The more complex example below uses load_script_textdomain_relative_path to generate a dummy script path that will not be found on disk. It then uses loco_compile_script_reference to force Loco Translate to honour it and produce the associated JSON.

function filter_script_textdomain_relative_path( $relative, $src ){
    if( preg_match('!/plugins/my-plugin/!',$src) ){
        $relative = 'dummy.js';
    }
    return $relative;
}

function compile_script_reference_for_my_domain( $bool $relative $domain ){
    if( 'my-plugin' === $domain && 'dummy.js' === $relative ){
        return true;
    }
    return $bool;
}

add_filter('load_script_textdomain_relative_path','filter_script_textdomain_relative_path',999,2);
add_filter('loco_compile_script_reference','compile_script_reference_for_my_domain',999,3);

See also

Last updated by