1

I want to provide the package @wordpress/hooks which currently resides in the core at wp-includes/js/hooks.js but I'm having a hard time finding exactly how / where it is enqueued so that I can copy this file, provide it with my plugin and if it's not already enqueued, enqueue it on my own.

How can I achieve this?

1
  • try to add ["hook"] in the dependences when you enqueue your script.
    – Kaperto
    Jan 3, 2020 at 12:27

2 Answers 2

0

I figured it out. To save you a long ass explanation, the hooks.js - wp-hooks file is registered as a default_script inside the load-scripts.php file. It's considered a default script and from 5.0, it's included with every install, but if you're looking to use this as a standalone script for 4.9 for example, do as follows:

  1. Grab the distribution file from: https://github.com/WordPress/WordPress/blob/master/wp-includes/js/dist/hooks.min.js (you need es-2015 polyfill from Babel for forEach and some as far as I see if your stuff is going to be used on <= IE11).
  2. Place it somewhere and just enqueue it the normal way under the name wp-hooks.

...and hope there are no conflicts.

That's it. You now have access to wp-hooks.

0

Please do not copy the file into your plugin/theme but use the WordPress library instead. When duplicating the hooks.js file, you have a huge problem, when another script loads the official hooks.js script on the same page. The second script will replace the wp.hooks logic of the first script (possibly deleting any JS hooks that were added already). Or even worse, you will get a JS error and the page does not initialize.

WP built an excellent logic to enqueue javascript that lets you define dependencies (i.e., tell WP which scripts need to be loaded, and in which order)

It's very easy to declare wp-hooks a dependency of your script, via the third parameter of wp_enqueue_script().

For example:

<?php
wp_enqueue_script(
    'your-script',
    'url/to/js/your-script.js',
    [ 'wp-hooks' ] // ← add this parameter.
);

Now, WordPress will automatically load 'wp-hooks' before your-script.js is loaded.

The second-best option is, to manually load the original wp-hooks script without a dependency. You could write above code like that:

<?php
// Manually load the wp-hooks script.
wp_enqueue_script( 'wp-hooks' );

// Later enqueue your-script.js, with the guarantee that wp-hooks is also loaded
wp_enqueue_script( 'your-script', 'url/to/js/your-script.js' );

The benefits of this approach:

  1. No duplicate script problem!!
  2. It's the official WordPress way!
  3. It works on front-end and in wp-admin
  4. wp-hooks is only enqueued when actually needed, WP handles all the checks
  5. You are guaranteed to have the latest version of the script available

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.