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?
2 Answers
Use a conditional wrapper in the above callback, e.g.:
function temp_enqueue_scripts() {
if ( ! is_admin() ) {
if ( 'custom-page.php' == get_page_template() ) {
wp_enqueue_script( 'jquery' );
}
}
}
add_action( 'wp_enqueue_scripts', 'temp_enqueue_scripts' );
Page template https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/
And is_page_template is a function that you can use to target the page, as your request is to enqueue your script or style.
add_action( 'wp_enqueue_scripts', 'wpse219924_enqueue_scripts' );
function wpse219924_enqueue_scripts()
{
if ( is_page_template( 'custom-page.php' ) ) //page template file name
wp_enqueue_script( 'site-script', get_template_directory_uri() . '/js/site.js', array( 'jquery' ), '20160707', true );
}
The same answer here https://wordpress.stackexchange.com/a/83860/18731