9

I have a custom page template where I would like to load some javascript. I suppose I could always include the javacsript 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.

22

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');
    } 
}
  • I am tring to use a javascript from one of my plugins and it says: Failed to load resource: the server responded with a status of 403 (Forbidden) – HOY Apr 2 '17 at 7:50
0

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; }

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.