One thing I recently heard for the first time (because I’m not really all that immersed in the current world of WordPress development) is that the Gutenberg block system that new versions of WordPress use is implemented in JavaScript. And it would appear that all the client-side work on WordPress is in JavaScript where possible.
This makes a lot of sense, frankly, only because the dominant language for browser experience tweaking has long been JavaScript and all the leading libraries and frameworks for client-side apps and UX are written with it.
This leads us to the question of how to throw some JavaScript of our own into web pages on our WordPress sites. Not having needed to do anything like this in a WordPress environment (if ever… since I’ve tended to use WordPress on content publishing sites, I’ve never needed to roll up my sleeves like that.
Three ways to add JavaScript to WordPress
There’s more than one way to add your JavaScript, as you might already have suspected. What everybody adds in any discussion of this sort of thing is that there’s also a fourth way, the Way of Darkness, where you actually start mucking about in native WordPress files. This is a bad business you should avoid, if for no other reason than that it’s going to get overwritten by a WordPress update at some point. So, having set the Way of Darkness aside, that leaves us three ways.
Just plunking it in
You’ll also find warnings about this approach, which is simply to use the newfangled block editor system to throw in a block of HTML. In that block, you write HTML, which includes throwing in a <SCRIPT> tag, a bunch of JavaScript, and then the </SCRIPT> tag.
Depending on what you’re trying to get done, I really fail to see what the problem is with doing it this way. It seems to work fine, it’s not going to bollocks up other JavaScript code running as part of WordPress (because you’re going to be careful about naming any variables you create in what is likely a global scope (I’m not actually quite sure that the code that runs in a page is running in an overall global scope, but I can’t think of any reason why it wouldn’t be).
This is the approach I’m using right now to create an on-page tool that calculates potential ROI for keyword SEO campaigns. It’s self contained, any data that might need to be stored from one session to the next will be stored somewhere other than WordPress (written to the localStorage object, for instance), and, hey, it seems to work OK. Maybe I’ll learn firsthand why this is a bad idea, or someone will kindly comment with an explanation.
Using a JavaScript plugin
As you’d expect, there are multiple plugins.
Leave a Reply