wp localize script – Localization of JavaScript which is only used in one page



  • WordPress 5.8
  • WPML: 4.4.10
  • DIVI: 4.9.4

What I am trying to achieve?

I have a JavaScript validation script which should validate input on the registration page. This script shows error messages. I want two things:

  • the strings should be managed/translated using WPML
  • the script should only be embedded in the registration page

What did I already achieve?

I added the following script to functions.php of my theme.

add_action('wp_enqueue_scripts', function() {
    // Register the script
    wp_register_script( 'register-validation-js', '/wp-content/themes/agreedo/js/register.js' );
    // Localize the script with new data
    $translation_array = array(
        'first_name_string' => esc_attr__( 'First Name 123', 'agreedo' ),
        'a_value' => '10'
    wp_localize_script( 'register-validation-js', 'object_name', $translation_array );
    // Enqueued script with localized data.
    wp_enqueue_script( 'register-validation-js' );
} );

At least I think so because when I analyse the sourcecode of any page I see the following:

<script type="text/javascript" id='register-validation-js-js-extra'>
/* <![CDATA[ */
var object_name = {"first_name_string":"First Name 123","a_value":"10"};
/* ]]> */
<script type="text/javascript" src="https://test.agreedo.com/wp-content/themes/agreedo/js/register.js?ver=5.8" id='register-validation-js-js'></script>

In the console I can enter: object_name.first_name_string and get “First Name 123”

enter image description here

So far so good.

I also successfully scanned the theme and see the string available in WPML:

enter image description here

Now is there a way to have this code only added to the registration page instead of all pages, because validation only takes place in the registration page?

Sources I used to accomplish this:

All examples refer to themes and the functions.php. I know this is a silly question from a beginner, but is there an equivalent to functions.php for a single page? Perhaps using a template page?

HHeckner 1 year 2021-07-28T01:18:11-05:00 0 Answers 0 views 0

Leave an answer