Use wp_localize_script for non existing script

How does core do it?

After thinking again about it, I thought there might be a case where WP does the same thing internally. And right: It does it.

Example ~/wp-admin/load-scripts.php

$wp_scripts = new WP_Scripts();
wp_default_scripts($wp_scripts);

// inside wp_default_scripts( &$scripts )
$scripts->add( $handle, $src, $dependencies, $version, $args ); // from WP_Dependencies
$scripts->localize( $handle, $object_name, $data ); // from WP_Scripts

This means, that there is a way, but only with using the internals directly.

So, to add & localize a non-existing file, you just do add false instead of $src:

$wp_scripts->add(
    'your_handle',
    false,
    array(),
    null,
    true
);
$wp_scripts->localize(
    'your_handle',
    "your_handle_object",
    array(
        'ajaxurl'    => admin_url( 'admin-ajax.php' ),
        'ajax_nonce' => wp_create_nonce( "your_handle-nonce" ),
        'action'     => "your_handle-action",
        'data'       => array(), // Whatever data you need to transport
    )
);

Leave a Comment