Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The supported way to inject JavaScript into WordPress is to enqueue it with wp_enqueue_script() from the correct enqueue action. For a normal website front end, that action is wp_enqueue_scripts. Use admin_enqueue_scripts for dashboard screens and login_enqueue_scripts for the login page. Keep reusable code in a file, attach small dependent snippets with wp_add_inline_script(), and let WordPress handle dependencies, versions, and placement.

Choose the WordPress context first

The hook determines where your script is allowed to load. Enqueuing a front-end file on an admin hook (or the reverse) makes debugging harder and can load code on pages where it does not belong.

Where the script runs Action hook Typical use
Public site pages wp_enqueue_scripts Site interactions, analytics, form enhancements, theme behavior
WordPress dashboard admin_enqueue_scripts Editor or settings-page controls
Login screen login_enqueue_scripts Login branding or validation UI

WordPress documents wp_enqueue_script() as the recommended way to link JavaScript to generated pages (function reference). Use a unique handle for every script.

Inject an external JavaScript file on the front end

1. Put the file in a predictable location

For a classic theme, create assets/js/custom.js inside the active theme. A plugin can use its own directory instead. Keep the file under version control and avoid editing a parent theme that will be overwritten by updates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

2. Enqueue it from wp_enqueue_scripts

Add this pattern to a child theme’s functions.php or, preferably for site-specific behavior, a small custom plugin:

<?php
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_custom_script' );

function mytheme_enqueue_custom_script() {
    wp_enqueue_script(
        'mytheme-custom',
        get_theme_file_uri( 'assets/js/custom.js' ),
        array(),
        '1.0.0',
        array( 'in_footer' => true )
    );
}

The handle (mytheme-custom) is the identifier WordPress uses for dependencies and inline additions. Replace the example path and version with values from your project. The Theme Handbook’s asset guidance shows this same enqueue pattern (Including Assets).

3. Add a dependency when your code needs one

If custom.js calls jQuery, list the registered handle instead of inserting a second copy:

wp_enqueue_script(
    'mytheme-custom',
    get_theme_file_uri( 'assets/js/custom.js' ),
    array( 'jquery' ),
    '1.0.0',
    array( 'in_footer' => true )
);

WordPress then schedules your file after the dependency. List every real dependency; do not rely on whatever order happens to appear in the page source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

4. Use a meaningful version

The version is sent as the script’s cache-busting query value. Increase it when you deploy a changed file, or derive it from the file’s modification time during development:

$path = get_theme_file_path( 'assets/js/custom.js' );
$version = file_exists( $path ) ? (string) filemtime( $path ) : '1.0.0';

wp_enqueue_script(
    'mytheme-custom',
    get_theme_file_uri( 'assets/js/custom.js' ),
    array(),
    $version,
    array( 'in_footer' => true )
);

Use a stable release version in production if your deployment process already handles cache invalidation.

Inline JavaScript: add only what must be inline

For a short configuration object or a few lines that belong to an enqueued file, use wp_add_inline_script() rather than printing a raw <script> tag from functions.php. The third argument is 'before' or 'after'; the default is 'after' (Theme Handbook guidance).

add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_custom_script' );

function mytheme_enqueue_custom_script() {
    wp_enqueue_script(
        'mytheme-custom',
        get_theme_file_uri( 'assets/js/custom.js' ),
        array(),
        '1.0.0',
        array( 'in_footer' => true )
    );

    $settings = array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'siteName' => get_bloginfo( 'name' ),
    );

    wp_add_inline_script(
        'mytheme-custom',
        'window.myThemeSettings = ' . wp_json_encode( $settings ) . ';',
        'before'
    );
}

Your external file can then read window.myThemeSettings.ajaxUrl. JSON encoding keeps strings and URLs in valid JavaScript syntax. If you must place an arbitrary value directly inside JavaScript, escape it for that context with esc_js(); WordPress’s security guidance explains context-specific escaping (Escaping Data).

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

When a direct inline hook is justified

Sometimes a tiny snippet must be emitted in a specific document region. wp_head() prints the wp_head hook output in the head, while wp_footer() prints the wp_footer output before the closing body tag (wp_head(), wp_footer()). These functions only work if the active theme calls them in its templates. A missing call means enqueued output and hook callbacks for that region may never reach the browser.

add_action( 'wp_footer', 'mytheme_footer_message' );

function mytheme_footer_message() {
    ?>
    <script>
        console.log('Footer script loaded');
    </script>
    <?php
}

Prefer an enqueued file or wp_add_inline_script() for maintainability, dependency ordering, and safer data handling. Use a direct hook only when the placement itself is the requirement.

Control placement and loading strategy

Footer placement

array( 'in_footer' => true ) asks WordPress to print a classic script in the footer queue. It is useful when the code does not need to run before the document body exists, but it still depends on the theme calling wp_footer().

Deferred and asynchronous loading

WordPress 6.3 added the $args options for in_footer and a loading strategy of defer or async (wp_enqueue_script()). Deferred scripts wait until the document has been parsed and execute in dependency order before DOMContentLoaded. Async scripts execute whenever each file arrives, so relative order is not guaranteed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
wp_enqueue_script(
    'mytheme-deferred',
    get_theme_file_uri( 'assets/js/deferred.js' ),
    array(),
    '1.0.0',
    array(
        'in_footer' => false,
        'strategy'  => 'defer',
    )
);

Choose async only when the script is independent of other scripts and of a particular execution point. Use defer for DOM work that should preserve ordering. Do not mark a dependency chain async unless every participant tolerates nondeterministic order.

JavaScript modules

For code using import and export, use WordPress’s module API rather than pretending a module is a classic script. See wp_enqueue_script_module(). Module dependencies and the import map are handled differently from classic handles; WordPress notes that modules using dynamic imports need footer placement or deferred loading so the import map is printed before evaluation.

Inject scripts in the dashboard or login page

Admin screens

Use admin_enqueue_scripts and check the supplied screen hook so your JavaScript does not load on every dashboard page:

add_action( 'admin_enqueue_scripts', 'myplugin_admin_assets' );

function myplugin_admin_assets( $hook_suffix ) {
    if ( 'settings_page_myplugin' !== $hook_suffix ) {
        return;
    }

    wp_enqueue_script(
        'myplugin-admin',
        plugin_dir_url( __FILE__ ) . 'assets/admin.js',
        array(),
        '1.0.0',
        array( 'in_footer' => true )
    );
}

Login screen

Use login_enqueue_scripts for assets needed only by wp-login.php:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
add_action( 'login_enqueue_scripts', 'myplugin_login_assets' );

function myplugin_login_assets() {
    wp_enqueue_script(
        'myplugin-login',
        plugin_dir_url( __FILE__ ) . 'assets/login.js',
        array(),
        '1.0.0',
        array( 'in_footer' => false )
    );
}
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pass data safely from PHP to JavaScript

  • Validate and sanitize incoming values before using them.
  • Prefer WordPress APIs for URLs, settings, nonces, and localized data.
  • Escape at the final output context; use esc_url() for URLs in HTML attributes and esc_js() for arbitrary values embedded in inline JavaScript.
  • Never concatenate untrusted request, database, or third-party content into executable code.
  • Keep secrets, API keys, and privileged credentials out of browser JavaScript.

WordPress summarizes these principles in its Security handbook. A nonce can help protect an authenticated action, but it is not a replacement for capability checks and server-side validation.

Common failures and fixes

Symptom Likely cause Fix
No script tag appears in page source The wrong enqueue action is used, or the theme omits wp_head()/wp_footer(). Use the hook matching the context and verify the active theme calls the required template function.
404 for the JavaScript file The URI does not match the real file location. Check the path with the browser network panel and use get_theme_file_uri() or plugin_dir_url() for the correct base.
Old code remains after deployment A browser, CDN, or WordPress cache still has the previous version. Change the enqueue version or use a file modification-time version during development, then purge caches according to your hosting setup.
Inline code runs before its library The snippet was attached to the wrong handle or placed before a dependency. Attach it to the handle it configures and choose 'after' unless the configuration must exist before evaluation.
Two copies of a library load A plugin or theme registered the same library under another handle. Inspect the generated HTML, reuse the existing registered handle, and declare your dependency instead of adding another URL.
Changing enqueue arguments has no effect The handle was already registered with different parameters. Use a unique handle or alter the original registration before enqueueing; enqueueing an already registered handle does not replace its original arguments.
Async code fails intermittently Execution order is nondeterministic. Remove async, use defer, or redesign the code so it has no ordering dependency.
Script works on the front end but not in the editor Admin and front-end hooks are separate contexts. Enqueue a dedicated admin asset on admin_enqueue_scripts and condition it to the required screen.

A practical debugging sequence

  1. View the page source and confirm the expected handle or file URL is present.
  2. Open browser developer tools, reload with the Network panel visible, and check the response status and content type.
  3. Check the Console for syntax errors, CSP violations, and undefined dependencies.
  4. Confirm the callback runs in the intended context and that its conditional checks are not returning early.
  5. Temporarily switch to a default theme in a staging copy only; if the script appears there, inspect the original theme’s template calls.

Performance and maintenance checklist

  • Load only on pages that need the behavior; use conditional tags or screen checks.
  • Bundle and minify in your build process, but retain readable source maps for development.
  • Declare dependencies instead of assuming another plugin’s load order.
  • Use one stable handle per logical asset and update its version when content changes.
  • Prefer a small external file for reusable logic; reserve inline code for page-specific configuration.
  • Test logged-out, logged-in, mobile, and cached views, because each can produce a different script path or execution state.
  • Keep WordPress, themes, plugins, and your JavaScript dependencies updated.

Or skip the browser setup

If your goal is to capture the rendered result of a WordPress page for documentation, visual QA, or an automated workflow, ScreenshotNeo returns a screenshot or PDF from one request instead of requiring you to install and maintain a headless browser. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all parameters. A minimal call for a public WordPress page is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Should the enqueue code go in a theme or a plugin?

Use a child theme for behavior that belongs to that theme; use a plugin for site functionality that should survive a theme change.

How can I prevent a script from loading on one page?

Return early from the enqueue callback with a conditional such as is_page(), or use the relevant admin screen check before calling wp_enqueue_script().

Can I add JavaScript without editing files?

A maintained plugin that registers and enqueues assets can work, but review its generated code, permissions, update policy, and conflict behavior before using it on production.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.