1

How do I add multiple JavaScript files to templates?

The below works great for only ONE Javascript file which loads on the templates called template-1.php and template-2.php - but I have another 3 JavaScript files.

  // Template ABC
  if ( is_page_template( array('template-1.php','template-2.php'))):
    wp_register_script( 'Name of JS File', 'https://url.js' );
    wp_enqueue_script('Name of JS File');
  endif;

Would the below be the correct approach if I wanted to add the other Javascript files to the same templates?

  // Template ABC
  if ( is_page_template( array('template-1.php','template-2.php'))):
    wp_register_script( 'Name of JS File', 'https://url.js' );
    wp_register_script( 'Name of NEW JS File 1', 'https://url-new-1.js' );
    wp_register_script( 'Name of NEW JS File 2', 'https://url-new-2.js' );
    wp_enqueue_script('Name of JS File');
  endif;
0

Although it's a better practice to merge all your JS files in a single JavaScript and enqueue it to reduce HTTP requests, it's alright to enqueue them separately too. So, you can register the script ( not required ) and then enqueue it.

Just enqueue all of the scripts after registering them, like:

  // Template ABC
  if ( is_page_template( array('template-1.php','template-2.php'))):

    wp_register_script( 'Name of JS File', 'https://url.js' );
    wp_register_script( 'Name of NEW JS File 1', 'https://url-new-1.js' );
    wp_register_script( 'Name of NEW JS File 2', 'https://url-new-2.js' );

    wp_enqueue_script('Name of JS File');
    wp_enqueue_script('Name of JS File 1');
    wp_enqueue_script('Name of JS File 2');
  endif;

Or directly enqueue them all:

  // Template ABC
  if ( is_page_template( array('template-1.php','template-2.php'))):

    wp_enqueue_script( 'Name of JS File', 'https://url.js' );
    wp_enqueue_script( 'Name of NEW JS File 1', 'https://url-new-1.js' );
    wp_enqueue_script( 'Name of NEW JS File 2', 'https://url-new-2.js' );

  endif;

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.