How can you add a custom script that needs to run only on the contact page of a site? The slug of the page is contact.
Link to the script directly from a template named page-contact.php using the get_header() template tag, like this:
get_header( '<script src="/my-script.js"></script>' );
Use functions.php to conditionally load the script by hooking it to wp_enqueue_scripts(), like this:
add_action( 'wp_enqueue_scripts', 'load_scripts' ); function load_scripts() { if ( is_page( 'contact' ) ) { echo '<script src="/my-script.js"></script>'; } }
add_action( 'wp_enqueue_scripts', 'load_scripts' ); function load_scripts() { if ( is_page( 'contact' ) ) { wp_enqueue_script( 'script', get_template_directory_uri() . '/script.js' ); } }
Link to the script directly from a template named page-contact.php, like this:
<head> <script src="/my-script.js"></script> </head>