DEV Community

Cover image for How to Use JavaScript Hook Adding Functions to a WordPress Plugin
WP Meta Box Plugin
WP Meta Box Plugin

Posted on • Originally published at metabox.io

How to Use JavaScript Hook Adding Functions to a WordPress Plugin

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:

Step 1: Create 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 js file of the plugin (which is in the dist > js folder).
  •  
  • webpack.config.js, package.json, and package-lock.json files are to build webpack.

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

Step 2: Install the @wordpress/hooks Package

Now, we need to install the @wordpress/hooks package to use JavaScript hooks in the created plugin.

@wordpress/hooks is an npm package. To install it, run the following command in the terminal of the created plugin's original folder:

npm install @wordpress/hooks --save

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';
Still in the script.js file, create a variation to use hooks. I created a variation using this code:
let globalHooks = createHooks();
Now you can start using JavaScript hooks in the plugin.

Step 3: Create the Main Feature for the Plugin

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() );

This time, the system will show an error message because you haven't installed webpack yet. Thus, move to step 4 to complete creating the plugin.

Step 4: Install webpack

To make the plugin run, we need to install webpack. Run the following commands one by one in the terminal:

     
  • The command is used to create the first content for the package.json file: npm init -y
  •  
  • The command is used to install webpack: npm install --save-dev webpack

After you run these commands, a new node_modules folder will be automatically created in the plugin. This plugin contains all the modules related to webpack.

Next, you need to install webpack with the following command:

npm install --save-dev webpack-cli

Then, open the package.json file and add the following declaration:

"scripts": {

    "build": "webpack",

    "watch": "webpack --watch"

},

This declaration is used to set up the command to build webpack (the npm run watch command).

Now you need to create the webpack.config.js file to set up the input js file and the output js file of webpack:

const path = require( 'path' );

const config = {

    mode: 'development',

    entry: './js/script.js',

    output: {

        filename: 'main.js',

        path: path.resolve( __dirname, 'dist' )

    }

}

module.exports = config;

Here, I set up the input file at the js/script.js path and set up the output file at the dist/main.js path.

OK, those are all we need to set up for webpack. Now, install the following command in the terminal to build webpack:

npm run watch

After you complete building webpack, the plugin can start working.

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.

Step 5: Use JavaScript Hook to Add an Advanced Feature for the Plugin

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!

In addition, you may like other articles about coding here.

Top comments (0)