Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 68 ยท Classic Themes and the Template Hierarchy

Enqueuing Styles and Scripts

Load CSS and JavaScript the WordPress way with wp_enqueue_style and wp_enqueue_script - handles, dependencies, versions, defer, localized data and conditions.

The quickest way to load a stylesheet is a <link> tag in header.php, and the quickest way to load a script is a <script> tag before </body>. In WordPress, that is also the quickest way to break things. Another plugin may load the same library, the order may be wrong, caching may serve stale files, and nobody can remove your tag without editing your theme.

WordPress solves this with an asset queue. You tell WordPress which files you need, what they depend on and where they go. WordPress sorts them, removes duplicates and prints the final tags at the right places. In this lesson you will learn the enqueue functions, handles and dependencies, versions for cache busting, footer and defer loading, passing PHP data to JavaScript, and loading assets only on the pages that need them. The runnable example is a plain-PHP stand-in for the queue, because WordPress itself cannot run on this site; the WordPress code in code blocks is read-only.

You should already know how a classic theme is organized from Your First Classic Theme, and the hook idea from Actions and Filters.

The one rule: never hardcode tags

Put this rule on a sticky note: do not write <link rel="stylesheet"> or <script src> in your templates for theme or plugin assets. Hand them to WordPress instead. The benefits are practical:

  • Dependencies are loaded in the right order (your script after jQuery, for example).
  • Duplicates are removed. Two plugins that enqueue the handle jquery produce one copy.
  • Other code can change things. A child theme can dequeue your stylesheet, and a performance plugin can add defer.
  • Printing is automatic. Styles go in wp_head(), scripts go in wp_head() or wp_footer(), depending on your settings.

For this to work, your theme must call wp_head() in header.php and wp_footer() in footer.php. Without those calls nothing is printed.

Enqueuing a stylesheet and a script

Attach your code to the wp_enqueue_scripts action. This hook name is used for scripts and styles even though it sounds scripts-only:

PHP
function mytheme_assets(): void {
    $theme_version = wp_get_theme()->get( 'Version' );

    wp_enqueue_style(
        'mytheme-main',
        get_theme_file_uri( 'assets/css/main.css' ),
        [],
        $theme_version
    );

    wp_enqueue_script(
        'mytheme-nav',
        get_theme_file_uri( 'assets/js/nav.js' ),
        [],
        $theme_version,
        [ 'in_footer' => true, 'strategy' => 'defer' ]
    );
}
add_action( 'wp_enqueue_scripts', 'mytheme_assets' );

Both functions take the same first four parameters:

Parameter Meaning
$handle A unique name for the asset, such as mytheme-main
$src The full URL of the file
$deps An array of handles that must load first
$ver A version string added to the URL as ?ver=...

The fifth parameter differs. For styles it is $media (such as 'all' or 'print'). For scripts it is $args, which can be a boolean for the old "in footer" flag or an array with in_footer and strategy.

There is also a split between registering and enqueuing. wp_register_style() and wp_register_script() tell WordPress about a file but do not load it. wp_enqueue_* with a handle you registered earlier loads it. Registering is useful for a library that only some templates need.

Handles and dependencies

The handle is the identity of an asset. It must be unique across the whole site, so use your own prefix (mytheme-, acme-slider-). WordPress bundles many libraries under well-known handles, including jquery, wp-element and wp-api-fetch. Listing one in $deps means WordPress loads it first, and loads it for you if nobody else did.

PHP
wp_enqueue_script(
    'mytheme-gallery',
    get_theme_file_uri( 'assets/js/gallery.js' ),
    [ 'jquery' ],
    '1.4.0',
    [ 'in_footer' => true ]
);

Dependencies are resolved recursively. If mytheme-gallery depends on jquery and jquery depends on jquery-core and jquery-migrate, all of them are printed first, in an order that satisfies every dependency. If a dependency handle does not exist, the dependent asset is not printed at all, which is a common reason for a script that "does nothing".

flowchart LR
    A["wp_enqueue_scripts fires"] --> B["Your code calls<br/>wp_enqueue_*"]
    B --> C["Queue of handles"]
    C --> D["Resolve dependencies<br/>and remove duplicates"]
    D --> E["wp_head prints<br/>styles and header scripts"]
    D --> F["wp_footer prints<br/>footer scripts"]

Your code only fills the queue. WordPress decides the order and prints the tags.

Versions and cache busting

Browsers cache CSS and JS aggressively. If you change main.css but keep the same URL, visitors may keep the old file for days. The $ver parameter appends ?ver=1.4.0 to the URL, so changing the version gives a new URL and forces a fresh download.

There are three common choices:

  • A fixed version string (like '1.4.0') that you bump with each release.
  • The theme or plugin version from wp_get_theme()->get( 'Version' ).
  • The file's modification time, which busts the cache automatically on every edit:
PHP
$path = get_theme_file_path( 'assets/css/main.css' );
wp_enqueue_style( 'mytheme-main', get_theme_file_uri( 'assets/css/main.css' ), [], (string) filemtime( $path ) );

Passing false (the default) makes WordPress append its own version number, and passing null adds no version at all. Leaving the version off entirely is a classic cause of "I deployed the fix but users still see the old page".

Scripts that run in <head> block the page from rendering until they download and execute. Two options keep your pages fast:

  • in_footer moves the script tag to the end of the page, right before </body>.
  • strategy adds defer or async to the tag (WordPress 6.3 and later). A deferred script downloads in parallel and runs after the HTML is parsed, in order. An async script runs as soon as it arrives, in any order.
PHP
wp_enqueue_script(
    'mytheme-analytics',
    get_theme_file_uri( 'assets/js/analytics.js' ),
    [],
    '1.0.0',
    [ 'in_footer' => true, 'strategy' => 'async' ]
);

WordPress is cautious about strategies. If a script with defer has a dependent that needs to run synchronously, WordPress falls back to the safer behavior so the dependency order is not broken. That is another reason to declare dependencies honestly. For ES modules, WordPress 6.5 added a separate pair of functions, wp_enqueue_script_module() and wp_register_script_module(), which print type="module" tags.

Passing PHP data to JavaScript

A script often needs values that only PHP knows: an endpoint URL, a nonce, a translated string. Two functions attach data to a script handle.

wp_localize_script() was designed to pass translated strings, and everyone uses it to pass data. It prints a JavaScript variable before your script:

PHP
wp_localize_script( 'mytheme-nav', 'MyThemeData', [
    'restUrl' => esc_url_raw( rest_url( 'mytheme/v1/' ) ),
    'nonce'   => wp_create_nonce( 'wp_rest' ),
    'labels'  => [ 'open' => __( 'Open menu', 'mytheme' ) ],
] );

The newer and more flexible wp_add_inline_script() adds any JavaScript before or after a handle. Pair it with wp_json_encode() to pass data safely:

PHP
wp_add_inline_script(
    'mytheme-nav',
    'window.MyThemeConfig = ' . wp_json_encode( [ 'sticky' => true ] ) . ';',
    'before'
);

The position is 'after' by default. wp_add_inline_style() does the same for CSS, which is handy for printing a few custom properties that come from settings. Both functions need a handle that is actually enqueued, because the extra code is attached to that handle.

Loading assets conditionally

Every file you load costs the visitor time. If only the contact page needs a map script, load it only there. Because wp_enqueue_scripts runs after WordPress knows which page it is serving, you can use conditional tags inside your callback:

PHP
function mytheme_conditional_assets(): void {
    if ( is_page( 'contact' ) ) {
        wp_enqueue_script( 'mytheme-map', get_theme_file_uri( 'assets/js/map.js' ), [], '1.0.0', true );
    }

    if ( is_singular( 'post' ) && comments_open() ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'mytheme_conditional_assets' );

Use different hooks for different screens: admin_enqueue_scripts for the dashboard (it receives the current screen suffix) and login_enqueue_scripts for the login page. Block-based code has its own tools, which later lessons cover.

You can also remove assets you do not want: wp_dequeue_style( 'handle' ) and wp_deregister_script( 'handle' ). Do it at a late priority on wp_enqueue_scripts, so the handle is already in the queue, and only for assets that you own or are sure about.

A queue you can run

WordPress's queue class (WP_Dependencies) is part of core, so the example below is a simplified stand-in. It registers assets, enqueues some of them, resolves dependencies depth-first, skips duplicates, and prints tags in the header or footer.

PHP Dependency-ordered enqueue queue (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You enqueued jquery but never jquery-core; it came in as a dependency of jquery. Both print in the header (they were registered with footer = false) before the footer scripts that need them. The gallery script appears once even though it was enqueued twice, and mytheme-broken is skipped entirely with a note about its missing dependency. Real WordPress keeps similar rules but adds more, such as handling of translations, script data and async fallbacks.

Common mistakes

  • Hooking into the wrong action. Use wp_enqueue_scripts for the front end. Enqueuing in init can work by accident, but is_page() and other conditions are not ready yet.
  • Reusing generic handles like main or script. Another plugin may use the same name and silently win.
  • Forgetting wp_head() or wp_footer(). The queue prints nothing without them.
  • No version. Visitors keep an old file after a deploy.
  • Loading big scripts everywhere. Add conditions so pages only load what they need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which action should you use to enqueue front-end styles and scripts from a theme?

    wp_enqueue_scripts is the hook for front-end styles and scripts. It runs after WordPress knows which page it is serving, so conditional tags work.
  2. 2. What does the $deps parameter do?

    Dependencies are handles that WordPress prints first. A missing dependency handle prevents the dependent asset from printing.
  3. 3. You want the browser to download a script in parallel and run it after the HTML is parsed. What do you pass?

    The defer strategy (WordPress 6.3+) keeps execution order and runs after parsing. Async runs as soon as the file arrives, in any order.
  4. 4. Why use filemtime() as the version of a stylesheet?

    A changed query string gives a new URL, which bypasses the browser's cached copy. The modification time changes automatically with every edit.
  5. 5. Which function prints a JavaScript snippet before or after an enqueued script?

    wp_add_inline_script() attaches code to a handle, with a position of 'before' or 'after'. The handle must be enqueued for the code to be printed.

Summary

  • Never hardcode asset tags. Enqueue on wp_enqueue_scripts so WordPress can sort, deduplicate and print them.
  • Give every asset a unique, prefixed handle and list its dependencies by handle.
  • Version your files (a release number or filemtime()) so browsers fetch changes.
  • Load scripts in the footer and use the defer or async strategy where the code allows it.
  • Pass data with wp_localize_script() or wp_add_inline_script() plus wp_json_encode().
  • Add conditions so each page loads only the assets it needs.

Next, build site navigation and widget areas in Menus, Widgets and Sidebars.