How to Use JavaScript Hook Adding Functions to a WordPress Plugin
Tags: wordpress, plugin, javascript
Published: 2021-05-11 08:15:21

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

<!--more-->

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

<h2>Applications of JavaScript Hooks in WordPress</h2>

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

<ul>

   <li>Add filters to the returned result of the plugin to return further information.</li>

   <li>Add variations for Gutenberg blocks.</li>

   <li>Add / remove attributes of blocks.</li>

   <li>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.</li>

</ul>

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 <strong>the name of the browser</strong> only. Then, I will use JavaScript hooks to add a filter to the plugin to get further information like <strong>the version of the browser</strong>.

This is how I do it:

<h2>Step 1: Create a Plugin</h2>

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

<img class="aligncenter" src="https://i.imgur.com/FaQnA1y.png" alt="Create a WordPress plugin to detemine the browser which users are using" width="649" height="241" />

<strong>Explanation</strong>:

<ul>

   <li><code>detect-browser.php</code> is the main file of the plugin.</li>

   <li>The <code>loader.php</code> file is to enqueue the js file of the plugin (which is in the <code>dist</code> &gt; <code>js</code> folder).</li>

   <li><code>webpack.config.js</code>, <code>package.json</code>, and <code>package-lock.json</code> files are to build webpack.</li>

</ul>

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

<h2>Step 2: Install the @wordpress/hooks Package</h2>

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

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

<pre>npm install @wordpress/hooks --save</pre>

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

<pre>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' )</pre>

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

<pre>import { createHooks } from '@wordpress/hooks';</pre>

Still in the <code>script.js</code> file, create a variation to use hooks. I created a variation using this code:

<pre>let globalHooks = createHooks();</pre>

Now you can start using JavaScript hooks in the plugin.

<h2>Step 3: Create the Main Feature for the Plugin</h2>

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 <code>getBrowser()</code> function in the <code>script.js</code> file. This is the function:

<pre>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;

}

</pre>

The <code>getBrowser()</code> function will return the name of the browser that you're using (<code>Opera</code>, <code>Chrome</code>, <code>Safari</code>, <code>Firefox</code>, <code>IE</code>).

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

<pre>console.log( getBrowser() );</pre>

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.

<h2>Step 4: Install webpack</h2>

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

<ul>

   <li>The command is used to create the first content for the <code>package.json</code> file: <code>npm init -y</code></li>

   <li>The command is used to install webpack: <code>npm install --save-dev webpack</code></li>

</ul>

After you run these commands, a new <code>node_modules</code> 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:

<pre>npm install --save-dev webpack-cli</pre>

Then, open the <code>package.json</code> file and add the following declaration:

<pre>"scripts": {

    "build": "webpack",

    "watch": "webpack --watch"

},

</pre>

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

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

<pre>const path = require( 'path' );

const config = {

    mode: 'development',

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

    output: {

        filename: 'main.js',

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

    }

}

module.exports = config;

</pre>

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

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

<pre>npm run watch</pre>

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:

<img class="aligncenter" src="https://i.imgur.com/Ri38cG4.png" alt="The plugin work without JavaScript hooks" width="1294" height="811" />

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

<h2>Step 5: Use JavaScript Hook to Add an Advanced Feature for the Plugin</h2>

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

Now the <code>getBrowser()</code> function has the following content:

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

}

</pre>

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

<pre>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;

}

</pre>

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

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

<img class="aligncenter" src="https://i.imgur.com/nhqS2c4.png" alt="The function is added to the plugin with JavaScript hooks" width="1296" height="784" />

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

You can refer to the source code of the plugin right <a href="https://github.com/wpmetabox/tutorials/tree/master/detect-browser">here</a>.

<h2>Last Words</h2>

In conclusion, in this article, we used the JavaScript hook to <strong>enhance the plugin feature</strong> to <strong>determine the browser</strong> which users are using. You can use this filter in the <a href="https://gretathemes.com/wordpress-themes/" rel="follow">WordPress theme</a>, 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 <a href="https://metabox.io/series/coding/">here</a>.