You should use the wp_enqueue_script()
function to first enqueue your script and then wp_enqueue_scripts
action hook to properly add your script to your footer or header of your theme.
Also, you should take a look at conditional tags and how they are used to load functions/scripts/styles/etc on a conditional basis.
So you would do something like this. First create a new file in your themes js folder and call it something like my-script.js. Open in up and add your scripts into that file. You are now ready to add the js file to your theme’s header/footer conditionally on a specific page with this function
function enqueue_my_scripts() {
if ( is_page( 42 ) //will check if we are on page ID 42, please see conditional tags or is_page_template( 'about.php' ) to check if the page template is about.php ) {
wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' )//only if script is dependant on jquery );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );