Enqueue scripts and styles correctly in WordPress
Adding JavaScript and CSS with <script> and <link> tags right in header.php is one of the most common mistakes of developers who come to WordPress from static HTML. It works, but it bypasses the WordPress asset system: no dependencies (your script may run before jQuery), duplicates (a plugin loads its own jQuery next to yours), no way for a child theme or a caching plugin to change the files.
Problem: Scripts and styles added directly to templates load in the wrong order, load twice, and cannot be changed by plugins or a child theme.
Solution: Register the files on the wp_enqueue_scripts hook with wp_enqueue_style() and wp_enqueue_script(). WordPress resolves the dependencies, removes duplicates by handle and prints the tags in the right place.
The basic pattern
In functions.php:
<?php
add_action( 'wp_enqueue_scripts', 'ha_enqueue_theme_assets' );
function ha_enqueue_theme_assets() {
$version = wp_get_theme()->get( 'Version' );
wp_enqueue_style(
'ha-main-style', // unique handle
get_stylesheet_uri(), // style.css of the active theme
array(), // dependencies
$version // version, for cache busting
);
wp_enqueue_script(
'ha-main-script',
get_stylesheet_directory_uri() . '/js/main.js',
array( 'jquery' ), // jQuery is loaded first
$version,
true // in the footer, before </body>
);
}
The version is added to the URL (main.js?ver=1.2.0). When it changes, browsers and CDNs download the new file instead of the cached one.
For files of the parent theme use get_template_directory_uri(), for the active (child) theme get_stylesheet_directory_uri().
Version from the file date
During development it is easier to take the version from the modification time of the file, so every change busts the cache automatically:
<?php $path = get_stylesheet_directory() . '/js/main.js'; wp_enqueue_script( 'ha-main-script', get_stylesheet_directory_uri() . '/js/main.js', array( 'jquery' ), filemtime( $path ), true );
Only where it is needed
A script needed on one template should not load on every page:
<?php
if ( is_page_template( 'templates/contact.php' ) ) {
wp_enqueue_script( 'ha-contact-map', get_stylesheet_directory_uri() . '/js/map.js', array(), $version, true );
}
Data from PHP is passed to a script with wp_localize_script() (or wp_add_inline_script()) after it is enqueued, not with inline <script> tags in the template.
NOTE: wp_enqueue_scripts runs only on the front end. For the admin use admin_enqueue_scripts (its callback receives the current admin page, so you can load files only on your own screen), and for the block editor enqueue_block_editor_assets.