WordPress Core documentation does not have any examples of this, and other ReadMe instructions only list the function names themselves. Other tutorials are specific to using Node or React, or for using Blocks on the WP Admin side. This page is to show how to use the WordPress Hooks API in regular JavaScript without any extra libraries or platforms.
Note: These examples will reference Nebula (this WordPress theme framework), but they are absolutely applicable for other themes and plugins!
Getting Started with the JavaScript WordPress Hooks API
This API is available on the WP Admin side without additional setup, but in order to be able to start using the WP Hooks API on the front-end in your JavaScript files, you’ll need to add the 'wp-hooks'
dependency when you register your script(s). If you don’t, you’ll see a 'wp' is not defined
error in your JavaScript console when you try to call wp.hooks
.
Like this:
register_script('nebula-whatever', get_template_directory_uri() . '/assets/js/nebula.js', array('jquery-core', 'wp-hooks'), '1.2.3', true);
Or with Nebula (to add defer and module types to the script):
nebula()->register_script('nebula-main', get_stylesheet_directory_uri() . '/assets/js/main.js', array('defer', 'module'), array('jquery-core', 'nebula-nebula', 'wp-hooks'), nebula()->child_version(), true);
Note that Nebula’s bundled child theme already added 'wp-hooks'
as a dependency to main.js.
WordPress Hooks API JavaScript Functions
Once you’re in your JavaScript file, you can start calling the JavaScript Hooks API. I’m going to cover the main two function types and each has two “sides” of the functionality.
These are simplified examples as a “quick start”, and functionality may change, although WordPress is notoriously backwards compatible. Keep an eye on the Gutenberg GitHub repo to monitor activity.
Important note: The “add_action” and “add_filter” functions must happen before the “do_action” and “apply_filters” hooks!! If you are working in imported modules, be very careful of race conditions. It is recommended to put all of your “add” hooks into the base JS file (such as main.js) so they are never “late” or missed by the actual action or filter.
wp.hooks.doAction()
Use wp.hooks.doAction()
where the “hooked” action should be executed (often in the parent theme). This allows child themes and plugins to “inject” their own functionality at this exact time. Be sure to give other scripts the opportunity to prepare before this doAction() triggers.
To implement the doAction function, use the following syntax:
wp.hooks.doAction('handle', argument);
The handle should be a string that others will use to “hook” into that action, and the argument is an optional parameter that can be passed to their usage.
Example usage:
let argument = 'This is a test string'; wp.hooks.doAction('example-action', argument);
wp.hooks.addAction()
To hook into an action from the child theme, a plugin, or another location you would use the wp.hooks.addAction()
function. While this line of code can appear wherever is convenient, make sure it is run before the action you are hooking into gets executed! These can be placed at the top-level of the JavaScript file (no need to wait for DOM ready or window load event listeners)– in fact, this is encouraged as the actions must be added prior to the execution of the doAction(), so avoid placing these in locations that require loading (like window load or inside modules) that may run after the action is excuted.
To implement the addAction()
, use the following syntax:
wp.hooks.addAction('handle', 'namespace', callback, priority);
The handle must match the handle used in the doAction()
and the namespace is a required string that identifies this instance– you can simply name it after your child theme or plugin, for example. The callback parameter is the function you want to execute at the time of the hook. The arguments set in the doAction()
are available to this callback. The priority, like the PHP hooks, is an integer that allows WordPress to determine the order of hook execution.
Example usage:
wp.hooks.addAction('example-action', function(arg){ console.log('The test arg is:', arg); //-> 'This is a test string' (from the above usage example) });
Important note: The “add_action” and “add_filter” functions must happen before the “do_action” and “apply_filters” hooks!! If you are working in imported modules, be very careful of race conditions. It is recommended to put all of your “add” hooks into the base JS file (such as main.js) so they are never “late” or missed by the actual action or filter.
wp.hooks.applyFilters()
The applyFilters()
hook allows child themes and plugins to modify data in the parent theme without needing to overwrite the entire function. This is great for lowering technical debt and improving maintainability of the codebase. Make sure that other scripts can actually prepare their hooks before this filter is applied!
Add this hook during a variable declaration using the following syntax:
wp.hooks.applyFilters('handle', content);
Note: additional arguments can be sent as extra parameters if necessary, but again this is meant to be a quick-start field guide. Refer to the Gutenberg GitHub repo for the official documentation.
Example usage:
let prefetchBlocklist = wp.hooks.applyFilters('nebulaPrefetchBlocklist', ['logout', 'wp-admin']);
wp.hooks.addFilter()
Finally, hooking into available filters is performed in the child theme or plugins with the addFilter()
function. While this line of code can appear wherever is convenient, make sure it is run before the action you are hooking into gets executed! These can be placed at the top-level of the JavaScript file (no need to wait for DOM ready or window load event listeners)– in fact, this needs to appear before the filter is executed, so it is encouraged to avoid placing this anywhere that requires loading (window load or even modules).
To implement the addFilter()
, use the following syntax:
wp.hooks.addFilter('handle', 'namespace', callback, priority);
The handle must match the handle used in the applyFilters()
and the namespace is a required string that identifies this instance– you can simply name it after your child theme or plugin, for example. The callback parameter is the function you want to execute at the time of the hook. The arguments set in the applyFilters()
are available to this callback. Remember to return inside of this function! The priority, like the PHP hooks, is an integer that allows WordPress to determine the order of hook execution.
Example usage:
wp.hooks.addFilter('nebulaPrefetchBlocklist', 'child', function(blocklist){ let newBlocklist = blocklist.push('yolo', 'whatever'); //If blocklist is an array return newBlocklist; });
The result of the two filter examples would set the prefetchBlocklist
variable to an array of ['logout', 'wp-admin', 'yolo', 'whatever']
.
Another Example:
This example shows how to append selectors to the Nebula button selector for analytics.
wp.hooks.addFilter('nebulaButtonSelectors', 'child', function(selector){ return selector += ', .header-callout-btn'; //Append to the string. Don't forget to start it with a comma! });
Important note: This hooks needs to happen before the Nebula analytics.js module is executed!! If you are putting this inside of usage.js in the child theme they may not run in time! It is recommended to place hooks directly in the DOM ready function of the main.js file inside the child theme!
Don’t forget you can trigger DOM events without this API
As an aside in closing, the doAction() event can be achieved with standard DOM events without needing the WP Hooks API at all. Example: jQuery(document).trigger('eventName', data)
where the data is whatever variable you choose.
With that method, you listen for it like any other event listener:
jQuery(document).on('eventName', function(data){ console.log('Do whatever here with:', data); });
This can be performed without jQuery as well, but since it is (and probably will forever be) bundled with WordPress, it does simplify the syntax.