How can I add my script to admin using script-loader.php?

I’m trying to load my custom script in the admin panel using the same method that WordPress itself loads scripts in the admin area.

This is an example script being loaded by wp-includes/script-loader.php:

$scripts->add(
    'password-strength-meter',
    "/wp-admin/js/password-strength-meter$suffix.js",
    array( 'jquery', 'zxcvbn-async' ), 
    false, 
    1
);

So I tried to add my own script by the same method. I :

  • Created a file named user-profile-validator.js inside /wp-admin/js/ (also created a minified version)
  • Tried to enqueue it by using the following code:

$scripts->add(
    'user-profile-validator',
    "/wp-admin/js/user-profile-validator$suffix.js",
    array( 'jquery' ), 
    false, 
    1
);

But nothing happened, it’s neither added to URL, nor I can find my script amongst loaded scripts.

Why is this happening?

PS: I’m doing a patch, that is why I’m modifying the core files.

1 Answer
1

I think you’e are only registering it with:

$scripts->add( 'user-profile-validator', ...)

but not enqueueing it.

Check e.g. how wp_register_script() is a wrapper for the WP_Scripts::add() method.

Additionally add:

wp_enqueue_script( 'user-profile-validator' );

in the relevant admin file to enqueue it or add it as a dependency for another enqueued script.

Note that password-strength-meter is a dependency for the user-profile script:

$scripts->add( 
    'user-profile', 
    "/wp-admin/js/user-profile$suffix.js", 
    array( 'jquery', 'password-strength-meter', 'wp-util' ), 
   false, 
   1 
);

that’s enqueued with :

wp_enqueue_script( 'user-profile' );

in the backend.

Leave a Comment