WordPress – Enqueue External Javascript File

WordPress - General Functions Javascript PHP

Snippet Overview

WordPress – Enqueue External Javascript File

Sometimes you need to add extra javascript files to your WordPress theme. This javascript file might assist with a specific effect you are attempting to replicate. Before you proceed, you first need to upload the js file into your theme’s directory. Unless you have built your own custom theme it is recommended that this file resides in a Child theme. This will ensure that any future theme updates do not remove it. I recommend adding a directory to your theme folder called js and then placing the file within that directory. Once the file is in place you need to enqueue it in either the header or footer portion of your site. To do this just add one of the following snippets of code to your theme’s functions.php file and configure the path of the file to match where you placed the js file in your theme.

Load Javascript in Header

This function will load the javascript file between your <header> and </header> in the rendered html.

// Enqueue External Javascript File in Header

function custom_header_scripts(){
  ?>
  <script type="text/javascript" src="https://www.website.com/wp-content/wp-content/themes/child-theme-name/js/script.js"></script>
  <?php
}
add_action( 'wp_head', 'custom_header_scripts' );

Load Javascript in Footer

This function will load the javascript file between your <footer> and </footer> in your rendered html.

// Enqueue External Javascript File in Footer

function custom_footer_scripts(){
  ?>
  <script type="text/javascript" src="https://www.website.com/wp-content/wp-content/themes/child-theme-name/js/script.js"></script>
  <?php
}
add_action( 'wp_footer', 'custom_footer_scripts' );

Load Javascript with Dynamic File Path

This function will dynamically map your child theme’s file path. All you need to specify is the directory and js file within.

// Enqueue with dynamic file path

function custom_scripts() {
    wp_enqueue_script('custom_javascript', get_stylesheet_directory_uri() . '/js/script.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'custom_scripts', 10 );
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply