Filter Hook since 4.1.0

script_loader_tag

Filters the final <script> tag markup for an enqueued script

Description

script_loader_tag is how you add async/defer or a nonce to a specific enqueued script without touching the theme's enqueue logic wholesale.

When it runs

During wp_head/wp_footer script printing, once per enqueued script handle.

Signature

apply_filters( 'script_loader_tag', string $tag, string $handle, string $src );

Parameters

  • $tag string — The <script> tag HTML.
  • $handle string — The script's registered handle.
  • $src string — The script's source URL.

Examples

Basic

add_filter( 'script_loader_tag', function( $tag, $handle ) {
    if ( 'my-script' !== $handle ) {
        return $tag;
    }
    return str_replace( ' src', ' defer src', $tag );
}, 10, 2 );

Add the defer attribute to one specific enqueued script.

Common Use Cases

  • Add async/defer to specific scripts
  • Add a nonce or crossorigin attribute
  • Remove type="text/javascript" for cleaner markup

Common mistakes

  • Deferring a script that other enqueued scripts depend on synchronously — breaks execution order

Related hooks

FAQ

Does script_loader_tag work for scripts I just echo manually?

No — only for scripts registered via wp_enqueue_script()/wp_register_script(). Manually echoed <script> tags aren't touched.

Source: wp-includes/class-wp-scripts.php

Group wizard

One session: this hook, then each related_hooks entry. Walk it and tell us what to change.

script_loader_tag → wp_enqueue_scripts

functions.php — script_loader_tag
functions.php
PHP script_loader_tag · Hook 1 of 2 · Step 1 of 6

Practice the script_loader_tag WordPress filter hook in our interactive sandbox — a VS Code-style editor with a step-by-step script_loader_tag tutorial, add_filter exercises, and instant feedback. No local WordPress install required.