I have in my plugin :

  • form.js : js script to do a custom validation on form fields
  • js_lang.php : based on this stackoverflow post
  • my-plugin-domain-fr_FR.po

In form.js, I use a var (msg_must_match) from js_lang.php

function inputsMatch( inputTypes, idInputReferring, idInputRepeat ){
        var inputReferring = document.getElementById( idInputReferring );
        var inputRepeat = document.getElementById( idInputRepeat );

        var checkPasswordValidity = function() {
            if (inputReferring.value != inputRepeat.value) {
                inputRepeat.setCustomValidity( msg_must_match /*<-- here*/ );
            } else {
        inputReferring.addEventListener('change', checkPasswordValidity, false);
        inputRepeat.addEventListener('change', checkPasswordValidity, false);

In my js_lang.php I try to manage the translation loading my-plugin-domain-fr_FR.po without success

$locale = "fr_FR";

setlocale('LC_ALL', $locale); 
bindtextdomain("my-plugin-domain", "./locale/");  
$str = 'It is must match with the previous input';
msg_must_match = "<?php echo gettext( $str ); ?>"

I do not manage to load correctly the .po file. Someone could help me ? Is there a easier wordpress way to do this ?


The WordPress way to do this is the wp_localize_script() function.

When you enqueue a script, also add a call to wp_localize_script():

wp_register_script( 'my-script', 'path/to/script.js' );
wp_localize_script( 'my-script', 'myScript', array(
    'msg_must_match' => __( 'Message must match', 'my-plugin-domain' ),
) );

This creates a global JavaScript object called myScript that will contain the keys and values passed as an array in the 3rd argument. So you can pass in strings using the WordPress translation functions, which will get translated just like any other string in your plugin.

Then in your script you can use those values for your strings:

inputRepeat.setCustomValidity( myScript.msg_must_match );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.