black friday sale

Hook is a common term with developers who often work with WordPress. It helps us expand the source code without editing themes or plugins. But, it’s the hook in PHP. In JavaScript, it's a bit different in use. So, we’re going to learn how to use JavaScript hook adding functions to a WordPress plugin!

Before getting started, let’s see what JavaScript hooks can do for us:

Applications of Javascript hooks in WordPress

You can use JavaScript hooks to add filters and actions in WordPress, for example:

  • Add filters to the returned result of the plugin to return further information.
  • Add variations for Gutenberg blocks.
  • Add / remove attributes of blocks.
  • Set the plugin to implement other actions in addition such as sending a request to save data when the plugin receives results from the webserver.

I have an example here for your better understanding. First, I create a plugin to determine the browser which users are using to access the website. The plugin returns the name of the browser only. Then, I will use JavaScript hooks to add a filter to the plugin to get further information like the version of the browser.

This is how I do it:

Creating a plugin

I created a plugin that has a simple structure as follows:

Create a WordPress plugin to detemine the browser which users are using

Explanation:

  • detect-browser.php is the main file of the plugin.
  • The loader.php file is to enqueue the JavaScript file of the plugin

In addition, in the js folder, I create a script.js file. It will be the js file of the plugin.

Installing the @wordpress/hooks package

The JavaScript hook is available in the @wordpress/hooks package. You can install this package as a dependency in your plugin like this:

npm install @wordpress/hooks

This package is also registered globally in WordPress under the handle wp-hooks. So you can also enqueue it to use like this without installing the NPM package:

wp_enqueue_script(
    'my-script',
    plugins_url( 'js/script.js', __FILE__ ),
    [ 'wp-hooks' ],
    '1.0.0',
    true
);

The @wordpress/hooks package has the following actions and filters:

addAction( 'hookName', 'namespace', 'functionName', callback, priority )
removeAction( 'hookName', 'namespace', 'functionName' )
removeAllActions( 'hookName' )
doAction( 'hookName', arg1, arg2, ... )
doingAction( 'hookName' )
didAction( 'hookName' )
hasAction( 'hookName' )
addFilter( 'hookName', 'namespace', 'functionName', callback, priority )
removeFilter( 'hookName', 'namespace', 'functionName' )
removeAllFilters( 'hookName' )
applyFilters( 'hookName', content, arg1, arg2, ... )
doingFilter( 'hookName' )
didFilter( 'hookName' )
hasFilter( 'hookName' )

After finishing the @wordpress/hooks package installation, you need to import this package into the plugin. Add this code to the top of the script.js file in the js folder of the plugin:

import { createHooks } from '@wordpress/hooks';
let globalHooks = createHooks();

If you only enqueue wp-hooks, you can simply do this:

let globalHooks = wp.hooks.createHooks();

Now you can start using JavaScript hooks in the plugin.

Creating a function

My plugin still doesn’t have any feature, so I will create one to determine the browser which users are using.

To add this feature to the plugin, I create a getBrowser() function in the script.js file. This is the function:

function getBrowser() {
    let result = '';
    if ( ( navigator.userAgent.indexOf( 'Opera' ) || navigator.userAgent.indexOf( 'OPR' ) ) != -1 ) {
        result = 'Opera';
    }
    else if ( navigator.userAgent.indexOf( 'Chrome' ) != -1 ) {
        result = 'Chrome';
    }
    else if ( navigator.userAgent.indexOf( 'Safari' ) != -1 ) {
        result = 'Safari';
    }
    else if ( navigator.userAgent.indexOf( 'Firefox' ) != -1 )  {
        result = 'Firefox';
    }
    else if ( ( navigator.userAgent.indexOf( 'MSIE' ) != -1 ) || ( !! document.documentMode == true ) ) {
        result = 'IE';
    }
    else {
        result = 'Unknown';
    }
    return result;
}

The getBrowser() function will return the name of the browser that you’re using (Opera, Chrome, Safari, Firefox, IE).

After that, call the getBrowser() function in the script.js file with the console.log command. This is the syntax:

console.log( getBrowser() );

Now open the Chrome Dev Tools on the front end, then you will see the result like this:

The plugin work without JavaScript hooks

As you can see, the plugin returned the name of the browser that I’m using, it’s Chrome.

Using a JavaScript hook

Do you remember the getBrowser() function in the script.js file we’ve created in step 3? In the returned result of the function, I will change the return result; code with the return globalHooks.applyFilters( 'detect_browser', result ); code. This code is to create a 'detect_browser' filter to change returned results.

Now the getBrowser() function has the following content:

function getBrowser() {
    let result = '';
    if ( ( navigator.userAgent.indexOf( 'Opera' ) || navigator.userAgent.indexOf( 'OPR' ) ) != -1 ) {
        result = 'Opera';
    }
    else if ( navigator.userAgent.indexOf( 'Chrome' ) != -1 ) {
        result = 'Chrome';
    }
    else if ( navigator.userAgent.indexOf( 'Safari' ) != -1 ) {
        result = 'Safari';
    }
    else if ( navigator.userAgent.indexOf( 'Firefox' ) != -1 )  {
        result = 'Firefox';
    }
    else if ( ( navigator.userAgent.indexOf( 'MSIE' ) != -1 ) || ( !! document.documentMode == true ) ) {
        result = 'IE';
    }
    else {
        result = 'Unknown';
    }
    return globalHooks.applyFilters( 'detect_browser', result );
}

Next, I’ll implement a hook to the 'detect_browser' filter to change the results. Add this code to the script.js file:

globalHooks.addFilter( 'detect_browser', 'myApp', filterGetBrowser );
function filterGetBrowser( browser ) {
    const { userAgent } = navigator;
    if ( userAgent.includes( 'Firefox/' ) ) {
        browser = `Firefox v${userAgent.split( 'Firefox/' )[1]}`;
    } else if ( userAgent.includes( 'MSIE/' ) ) {
        browser = `IE v${userAgent.split( 'MSIE/' )[1]}`;
    } else if ( userAgent.includes( 'Chrome/' ) ) {
        browser = `Chrome v${userAgent.split( 'Chrome/' )[1]}`;
    } else if ( userAgent.includes( 'Safari/' ) ) {
        browser = `Safari v${userAgent.split( 'Safari/' )[1]}`;
    }
    return browser;
}

The filterGetBrowser function hooks to the 'detect_browser' filter. It will return the entire information of the browser that the user is using.

After adding the filter, we need to run webpack again. Then, back to the front end and open the Chrome DevTools to check the result:

The function is added to the plugin with JavaScript hooks

In addition to the browser name (Chrome), the plugin returned the version of the browser (v90.0.4430.72). So the filter added by the JavaScript hook worked well.

You can refer to the source code of the plugin right here.

Last Words

In conclusion, in this article, we used the JavaScript hook to enhance the plugin feature to determine the browser which users are using. You can use this filter in the WordPress theme, or use it for further processing like getting the version of the browser.

This is just one of many applications of JavaScript hooks in WordPress. Have you ever used JavaScript in any other case? Share it with us in the comment section below.

3 thoughts on “How to Use JavaScript Hooks In WordPress

  1. Really good read!

    enjoyed your article.
    Didn't know that I could use the action and filter hooks in the JS world as well.

    Do you plan to using these hooks in the Metabox plugins and extensions?

    - Rao

    1. Hi Rao,

      Currently, the demand for it is little in Meta Box. We'll see if we need this feature in the plugin.

  2. Thank you for the Coding articles. They are very helpful.

    If possible please write your guide for the points:
    1) techniques to include and manage css files (as usually we have them near the js and php)
    2) guide for use all them in one place, when you work with wp theme and plugins in the same project (should we use for plugin and for the theme individual separate settings for composer, autoload and etc ?)

    Waiting for your articles for your preferred techniques

Leave a Reply

Your email address will not be published. Required fields are marked *