I put one javascript file in the header.php file and that page that
uses that file works (the home page)
Don’t do that. Use wp_enqueue_script()
instead.
You can use conditional tags to load scripts and styles in the desired locations. For example, to check if a particular page template is being used, you’d use is_page_template()
.
Scripts and styles can be registered on the wp_loaded
hook, then enqueued on the wp_enqueue_scripts
hook:
// Register scripts/styles. They can be optionally enqueued later on.
add_action( 'wp_loaded', 'wpse248829_register_scripts' );
function wpse248829_register_scripts() {
wp_register_script( 'character-counter-script-js', get_template_directory_uri() . '/js/char-counter.min.js', array( 'jquery' ), false, true );
wp_register_script( 'tweet-counter', get_template_directory_uri() . '/js/tweet-counter.min.js', array( 'jquery' ), false, true );
wp_register_script( 'title-tag-counter-script', get_template_directory_uri() . '/char-counter/js/title-tag.min.js', array( 'jquery' ), false, true );
wp_register_script( 'description-counter-script', get_template_directory_uri() . '/js/description-tag.min.js', array( 'jquery' ), false, true );
}
// Enqueue scripts/styles.
add_action( 'wp_enqueue_scripts', 'wpse248829_enqueue_scripts' );
function wpse248829_enqueue_scripts() {
// Load everywhere.
wp_enqueue_style( 'style', get_stylesheet_uri() );
// Probably not needed, because it was already specified as a dependency.
// wp_enqueue_script( 'jquery' );
// Only enqueue scripts/styles on static front page.
if ( is_front_page() ) {
wp_enqueue_script( 'character-counter-script-js' );
}
if ( is_page_template( 'tweet-template.php' ) ) {
wp_enqueue_script( 'tweet-counter' );
}
if ( is_page_template( 'title-tag-template.php' ) ) {
wp_enqueue_script( 'title-tag-counter-script' );
}
if ( is_page_template( 'description-tag-template.php' ) ) {
wp_enqueue_script( 'description-counter-script' );
}
}