WordPress Javascript: A Beginner’s Guide

If you ask one million web developers what JavaScript is, you’ll get one million different answers back. Pretty much everything interactive on the web is done using JavaScript.

As a modern content management system (CMS), WordPress and many of its plugins partially rely on JavaScript to get the job done. Contrary to what it may sound like, JavaScript has no relation to the Java programming language. It’s only called that for marketing purposes.

Let’s dive into everything you need to know to harness the combined power of JavaScript and WordPress.

In This Guide

What Is JavaScript?

In a nutshell, JavaScript is one of the most popular programming languages used on the web. JavaScript can be used to build dynamic websites, web/mobile apps, real-time networking applications like chats, command-line tools, and even games.

A long time ago, the Internet relied on HTML and CSS exclusively. This combination allows for very basic styling of content. However, very little could be done to make content dynamic  and creating web applications was out of the question.

Since servers were far more expensive to maintain, developers decided to write JavaScript to operate on the client machine. Written in a similar manner to other functional programming languages, JavaScript can take data into functions, process it, and output data.

Web browsers have a JavaScript engine that knows how to execute JavaScript code. For example, the JavaScript engine in Chrome is v8, while the FireFox JavaScript engine is SpiderMonkey. For this reason, Javascript relies on browsers to “understand” how to interpret, handle, and manipulate the display of data.

The Technical Aspects of JavaScript

Interested in knowing more about the tech behind JavaScript? There are a few important differentiators to know for those who have experience in other types of development. First, JavaScript is type-agnostic like PHP. That means that its variables don’t have a defined type, and any given variable can be assigned to almost any type of value.

Most modern languages are “object-oriented”, meaning that they rely on reusable “classes” that represent a literal object. The closest that JavaScript comes to this is through “prototypes”. These data structures can be reused and can hold certain values, but their functionality and usability are far more limited than languages built around the object-oriented concept, like Java.

What Does JavaScript Do?

Because of the huge community support and investment from big companies like Facebook and even Netflix, JavaScript can do much more than operate within web browsers. JavaScript can do something as simple as grabbing the current year to display next to the copyright symbol on a website, and more complex work such as doing the bulk of the processing for an online image editor.

In a nutshell, JavaScript does nearly whatever the developer wants it to do on the client’s machine. JavaScript caches locally on the client machine when the client visits a site that uses it.

While sensitive data has to be handled on the server, many web-based applications heavily utilize JavaScript to take advantage of the client machine’s processing power. Now that we’re in the era of endless “frameworks” that make developing various types of content much faster, the possibilities are infinite.

Is JavaScript Safe?

Like the majority of protocols and older languages, JavaScript was not initially built with security in mind. This is a perfectly reasonable thing to wonder, given how prevalent cyberattacks have become. 

There are browser extensions like “NoScript” that simply block all JavaScript code from executing. As long as you follow the general rule of the web and don’t visit untrusted sites, it’s fine to allow JavaScript to run.

Because it’s a programming language, of course malicious users can abuse it to attack your computer. Modern browsers will automatically detect most of these attacks. If you’re concerned about security with WordPress JavaScript, you may get some peace of mind with a WordPress security plugin that puts most aspects of website security on autopilot.

Two Major JavaScript Attack Types

The adage “keep your friends close and your enemies closer” is pertinent when it comes to development and security. It’s very important to understand how the bad guys take advantage of JavaScript so you can thwart their efforts!

Cross Site Scripting (XSS)

Cross-site scripting (XSS) is a type of malware attack that’s executed by exploiting cross-site vulnerabilities on any WordPress site. In fact, it’s the most common way for WordPress sites to be hacked because there are so many WordPress plugins that have XSS vulnerabilities.

A cross-site scripting attack is used if a page allows data to be submitted on it. In this attack, the malicious user places JavaScript code in the data to be submitted onto a page accessible to the public.

If no mitigation measures are in place, this malicious code actually runs the JavaScript code on anyone’s computer who visits that page. This is why it’s important to “sanitize” input. This means, before it’s posted,  you remove things like brackets and quotes that would render the code useless.

Cross Site Request Forgery (CSRF)

This type of attack takes advantage of web pages you might already be logged into. The most common scenario would involve you being logged into your bank.

Say you’re logged into your bank account but then decide to go on a torrent website that has CSRF ready to go. CSRF, in the absence of browser mitigations, adopts the link pattern to do things like bank transfers for every major bank, then runs them on your machine in the background.

One scenario that actually happened with a major site and a major bank was that the bank’s link to transfer money looked like: www.bankwithbadsecurity.com/transfer&amount=1000&toAccount=12345 to transfer $1,000 to an account numbered 12345.

To the bank, it looks like you requested it, and because the request would come from your IP address, it’s hard to prove you didn’t initiate it. Fortunately, most modern browsers will automatically detect this and prevent it.

Can I Use JavaScript Inside Of WordPress?

Yes, you can use JavaScript when you’re developing for WordPress. Keep in mind that WordPress is a flexible content management system that has two editing modes. One of them allows you to directly edit code, and the other allows you to use an editor similar to what you might see on a word processor, also known as a “WYSIWYG” editor. In the most recent version of WordPress, the WYSIWYG editor is called Gutenberg.

Keep in mind that you can also use JavaScript when you develop extensions for WordPress. While the server-side of WordPress is PHP, the client-side is almost 100% of the time JavaScript.

Should I Learn JavaScript For WordPress?

The answer to these questions depends on what you intend to do with WordPress. If you just want a few static pages you generate using the platform, you’d likely be fine without learning JavaScript.

On the upside, it’s pretty easy to get started with JavaScript, and you’ll also learn a lot about how HTML and CSS work. However, in addition to WordPress training, you’ll want to work on learning JavaScript if you want to make a dynamic and memorable site. 

A quick warning: if you’re a beginning web developer, do not expect to master JavaScript in a matter of days. JavaScript is notorious for having very vague error messages and it’s often criticized for being “spaghetti code.” This means that over the years, developers have piled on lots of code without properly organizing it. On top of that, most developers learn how to program in frameworks that use JavaScript but are syntactically a bit different.

You should especially invest time in learning JavaScript if you are a freelancer or agency who manages clients’ sites. While there are top-notch tools that allow you to manage multiple WordPress sites, no plugin can make the sites for you!

In addition, if you have aspirations to be a web developer, learning JavaScript is beneficial for these careers:

  • Front-end Developer
  • Back-end Developer
  • Full-stack Developer

In addition, learning JavaScript, along with more advanced HTML, CSS, and PHP serve as a solid WP foundation that will likely cut down on overhead costs for you. You will no longer need to pay outside contractors, cutting into your bottom line, to perform tasks that in reality may take minutes to complete. Once you master JavaScript, you can move on to popular frameworks, such as React and Angular, to make truly unique, responsive applications within WordPress.

How Do I Write JavaScript When Coding In WordPress?

Even though adding JavaScript to a WordPress site isn’t as straightforward as adding CSS and HTML, it won’t take you long to get started. There are two different ways to approach it, and each has a different purpose.

Method 1: On Every Page

If you’re looking to run the same script on every page of your WordPress site, adding the code manually to each page would be pretty tedious, to say the least. The proper place to insert JavaScript within HTML is within the header and footer of the page.

There are a few free plugins that will take your customized JavaScript and drop it in the header and/or the footer of every page on your WordPress site. WordPress admins love these plugins because they work perfectly with Google Analytics, ensuring that every page hit is counted, helping boost SEO rank faster.

Method 2: Different JavaScript on Each Page

Let’s say you’re running a WordPress site that has a different tool on each page that relies on at least one “library” to function. Forcing all of your JavaScript to load on every single page, especially when it’s not needed, will simply slow down access to your site. Common sense tells us that slowing down your visitors’ experience isn’t the best way to win over business!

There are plenty of tutorials on the web that have insanely complicated methods of performing this process. While it’s true that this can be done by making complex edits within your functions.php file, there’s no real need to take this approach unless you enjoy headaches.

Instead, install the Code Embed plugin on your site. This will enable you to add JavaScript and embed it wherever you’d like within the page.

Using the CodeEmbed Plugin

After installing the Code Embed plugin, go to Screen Options and hit the checkbox that says “Custom Fields”. This will allow you to add your JavaScript to the page.

On the editing page, you will see a box that says “Custom Fields”, with an option to “Enter New” custom fields. Click on that, and you’ll have empty textboxes to enter the name of your JavaScript code, as well as for the code itself.

To avoid conflicts with existing WordPress codes, you must begin the name of your JavaScript code with the capitalized letters “CODE”. Something like “CODEtimer” would be fine. Then you’ll add the actual JavaScript into the other box. Make sure that you include the script opening and closing tags!

Once you’re done, just click the button that says “Add Custom Field”. Finally, identify where on the page you’d like the JavaScript code to execute. For example, if the code loads a timer, find where on your page you’d like to insert that timer. You’ll then use the exact syntax [[CODEtimer]] to have WordPress insert your JavaScript there, and you’re done!

How Do I Include My JavaScript and CSS Files in WordPress?

Though WordPress has built-in themes, many web developers prefer to have a more unique design and will use their own CSS. You’ll also need a way to store those JavaScript files.

In this portion, you’ll need to head to your File Manager and locate the file called “functions.php”. Note that this will be in the folder where the base theme for your site is located.

Adding CSS to functions.php

Once you’re in the functions.php file, follow these steps:

  1. On a new line, create an empty function by adding the code function
    addMyCSS() { #Fill This In Later }
  2. “Register” your CSS file with WordPress by using the built-in function called wp_register_style in the next step
  3. Remove the filler we put in to the code and instead put wp_register_style('name_of_css_style',plugins_url('file-location.css',__FILE__));
  4. We have now told WordPress what to call our CSS style and where it is. Now it’s time to “enqueue” the style, or tell WordPress we are ready to use it.
  5. Staying within the addMyCSS function block, add the code wp_enqueue_style(‘name_of_css_style’); right below the code we entered in the last step.
  6. There’s one final step, but first, make sure that you are OUTSIDE of the entire function that we created and in the general portion of the PHP file.
  7. Outside of addMyCSS, simply add the following line: add_action('wp_enqueue_scripts','name_of_css_style');. This tells WordPress to trigger the loading of this file on page load.

You might be wondering why we have wp_enqueue_scripts in the add_action function for a stylesheet. This is simply the way WordPress has always implemented the feature.

Adding JavaScript files to WordPress

Now that we’ve gone over the process of generating a function, registering a file, and adding an action, this part should be a piece of cake!

  1. Make a function in functions.php called addMyJS just like we did with addMyCSS.
  2. We will utilize the function wp_register_script, but it’s a bit more complex. It has five “parameters” (the items put into parentheses). Look below to see what each parameter is.
  3. wp_register_script(1. Your Script Name, 2. plugins_url(location_of_script.js, __FILE__), 3. array of JS dependencies, usually array(jquery), 4. (Optional) version of your JS file in single quotes, 5. should be true if you want the JS in your footer, false if you want it in the header);
  4. Here’s a practical example of some JavaScript to run in the footer of a theme: wp_register_script('timer_js', plugins_url('timer_file.js', __FILE__), array('jquery'),'1.0', true);
  5. Again, OUTSIDE of our addMyJS function, “enqueue” your script by putting this in your general area of the PHP: add_action( 'wp_enqueue_scripts', 'addMyJS' );

It might look complex, but once you get the hang of it, it’ll take under a minute, so have no fear!

What Plugins Can I Use to Add JavaScript to WordPress?

There are many completely free plugins just for this purpose. Each works slightly different, so you experiment with a few before you commit. Here are five major ones to try out.

  • ASync – Uniquely, this plugin loads both your JS and CSS files separately from the rest of your page. This can be particularly helpful if there’s a coding error that would otherwise indefinitely stop your page from loading.
  • JS in Widgets – Just need to add a few lines of codes for something like Google Analytics? This plugin takes the hassle out of it and will allow small snippets to be added to your WordPress sites.
  • Zia CSS/JS Helper – This one is by far the best for those experienced with classic HTML/CSS/JS web development. It makes your WordPress editing functionality just like editing a site through cPanel’s file manager. You can utilize inline CSS and JavaScript to quickly add bits of code, create and manage external files, and more.

Always Backup Your Site First!

While the vast majority of WordPress plugins will do your site no harm, there’s always a chance that you’ll run into problems. Before you install any additional plugins or modify your site, make a backup of your site using a WordPress backup plugin that can handle complete backups of your WordPress installation, like BackupBuddy. Save yourself hours of possible rework and ensure all your hard work doesn’t go to waste.

Can I Utilize WordPress APIs Using JavaScript?

As you may know, WordPress has an extensive series of APIs, or Application Programming Interfaces. APIs are essentially server-side functions that you can utilize in languages like JavaScript. The newer, more modern method for developers to learn WordPress API functionality is through the WordPress WordPress APIs Code Reference page.

This is where we got those “built-in functions” we used earlier. We could go on for days about each function in the APIs and how they work in tandem with JavaScript. However, that is an advanced topic that simply requires individual time and dedication to learn.

Are There JavaScript Libraries Tailored for WordPress?

Yes! Recognizing that many developers have not mastered the entirety of WordPress API content, many programmers have made JavaScript libraries that can be easily embedded, using any of the plugins we discussed before.

Most JavaScript libraries are found on GitHub and are completely free. There are hundreds of thousands of available JavaScript libraries compatible with WordPress, ranging from one that adds fun effects to WordPress to one that lets you make a site with a very similar layout to Pinterest!

The most well-known library used with WordPress (and most sites) is called jQuery. jQuery takes the complexity out of JavaScript and once you get the hang of it, you will be writing functions quickly and easily.

Help! My WordPress JavaScript Isn’t Working!

One of the less fortunate parts of JavaScript is that errors aren’t obvious. And adding WordPress on top of that can make it quite confusing.

Some errors can be caused as easily as a forgotten quotation mark. Others can be caused by major coding errors not so easily identified. So, how do professional developers tell the difference?

There are two main keys to troubleshooting: the console.log JavaScript function and the browser debugging console. Chrome’s console in particular is great for this.

console.log

This can be used to see what the value of a variable is at a given point in a function and ensure that parts of functions are actually being reached. Within a JavaScript file, you simply would put something like console.log("test");.

The Debugging Console

Depending on the browser being used, the console’s setup will be different. Generally, you just need to hit F12 to open it, then click on the “Console” tab.

The console will show what line, of what JavaScript file, there was an error. It usually shows the full “stacktrace”, or the series of files to go through until you hit the culprit. This is also where your console.log messages print.

Wrapping Up: JavaScript + WordPress

There are professional tools that will give you far more insight, but these usually cost a pretty penny. The good news is that as you scale up as the world’s next greatest WordPress JavaScript developer, tools will scale with you!

WordPress JavaScript

Spread the love

Posted by News Monkey

blank