Localization of JavaScript which is only used in one page

Environment:

  • 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
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

So far so good.

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

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?

Topic wp-localize-script Wordpress

Category Web


You can add conditional statements inside the wp_enqueue_scripts action hook.

add_action( 'wp_enqueue_scripts', function() {
   if( is_page( 'page-slug' ) ) {
      // Enqueued script with localized data.
      wp_enqueue_script( 'register-validation-js' );
   }
} );

You can refer to the is_page documentation for more information on what arguments can be pass.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.