How to load javascript on custom page template?

The question:

I have a custom page template where I would like to load some javascript. I suppose I could always include the javascript in the actual file, but that seems ugly. Is there any way to identify if WordPress is loading my custom-page.php file so I can enqueue the script only on that page?

It should work dynamically, so checking page id is not an option.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use is_page_template to check if you template is being used and load your scripts based on that ex:

Add this code to your functions.php:

add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');
function Load_Template_Scripts_wpa83855(){
    if ( is_page_template('custom-page.php') ) {
        wp_enqueue_script('my-script', 'path/to/script.js');
    } 
}

Method 2

You can use something like this …..

 add_filter( 'template_include', 'wpm_load_script_for_template', 1000 );
        function wpm_load_script_for_template( $template ){
             if(is_page_template('lead_capture_full.php')){

// standard code for adding js

            }
        return $template; }

Method 3

You can add new wp_enqueue_scripts in your template file before get_header() call:

/**
 * Template name: My page
 */

function my_page_scripts(){
    wp_enqueue_script('my_script', get_template_directory_uri() . '/js/my-page-script.js', [], '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'my_page_scripts' );

get_header();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment