JavaScript for WordPress People: What You Need to Know

JavaScript for WordPress People: What You Need to Know

At December 2015’s WordCamp US, WordPress co-founder Matt Mullenweg used his State of the Word talk to exhort us to “learn JavaScript, deeply.” But what does this mean and what do WordPress developers need to know about JavaScript?

JavaScript is an established and continually growing front-end language that’s traditionally been used to create animations and effects on web pages. Chances are if you’ve got a plugin on your site for a slider, social media links or responsive navigation menu, it uses JavaScript to create the effects.

If you’re a WordPress developer accustomed to working with PHP, you may never have touched a line of JavaScript and may be feeling somewhat intimidated by the prospect of delving into it.

But the good news is that PHP and JavaScript have their similarities. They work in different ways and different contexts, but the code you write isn’t always all that different.

In this post, I’ll outline some of the key JavaScript concepts that WordPress developers need to understand to start working with it. I’ll cover:

But let’s start with a quick introduction to JavaScript and why it’s becoming so popular.

What is JavaScript Anyway?

JavaScript is a front end programming language (also referred to as client-side), which means that it communicates with a user’s web browser when they visit your site. This is the main difference between JavaScript and PHP, which is a back-end (or server-side) language, meaning it communicates with the server. This means that sites powered by JavaScript have the potential to run much faster and be more responsive:

  • If your site uses PHP to respond to something your users do, a request will go to the server to process that change and then the page will refresh with the change activated.
  • If you use JavaScript, the browser processes the changes, meaning that a request doesn’t have to go to the server and the page doesn’t refresh.

You can imagine the advantages this can bring: cutting out all those server requests can make your site run much faster and can give you the flexibility to create web-based applications that work a lot like desktop programs.

In fact, as a WordPress user, you’re already using one of those as the WordPress software uses JavaScript to power the backend admin screens. If you’ve ever dragged and dropped items onto your menus, created widgets or used the Customizer, then you’ve benefited from the JavaScript that powers the WordPress admin.

But this doesn’t mean using Javascript is always better than PHP. Sometimes you might want the server to refresh the page, for example if you want to generate new pages and URLs for SEO purposes (although there is a way around this in JavaScript).

The other potential downside of using JavaScript is that it won’t work if your users don’t have JavaScript enabled in their browser. Modern browsers (both desktop and mobile) do work perfectly well with Javascript but if your user has an older browser, or your JavaScript doesn’t play nicely with their version of Internet Explorer, or they’re using accessibility tools that require JavaScript to be turned off, then nothing you add via JavaScript will work. So it’s a good idea to have a server-side fallback, just in case.

Finally, it’s important to remember that markup generated using JavaScript after the page has loaded won’t always be crawled by search engines. So if something’s crucial for your search engine rankings, either add it using a server-side language or use a JavaScript method that search engines can read.

JavaScript and WordPress

As a WordPress developer, you don’t need to know everything about JavaScript, you just need to know what’s relevant when working with WordPress.

So let’s take a look at the uses of JavaScript with WordPress and how the two interact with each other.

1. JavaScript is Already Part of WordPress

JavaScript already comes bundled with WordPress, in the form of numerous JavaScript libraries, such as jQuery, JSON, Backbone.js and Underscore.js.

It can be daunting looking at this list and wondering where to start, so I’d recommend focusing on jQuery first. jQuery is a vast library that makes programming with JavaScript easier and more reliable (enhancing browser support, for example), and if you’re adding animations or effects to your site via your theme or a plugin, then jQuery is probably the tool you’ll use to do it.

Once you’ve got some experience with JavaScript by using jQuery, you’ll know how scripts work and be ready to move on to using JSON to interact with the WP-REST API. More of this later in this post.

2. JavaScript is in Plenty of Plugins and Themes

You’ve probably got plugins installed on your site that use JavaScript to create effects and animations, or maybe to handle data or insert content dynamically. It’s also in plenty of themes, either powering effects on the front-end or making your interaction with the theme more dynamic in the admin screens.

3. JavaScript Powers the WordPress Admin

JavaScript has become increasingly fundamental to the WordPress admin in recent releases and is likely to become even more important  in the future, especially with the release of Calypso, an entirely JavaScript-powered version of the WordPress admin.

Everything you do in the admin screens that result in immediate changes will be using JavaScript, including:

  • Creating and editing menus
  • Creating and editing widgets
  • Updating plugins and themes
  • Using the Customizer.
WordPress Customizer screen
The Customizer uses JavaScript

It’s only when you click on the PublishUpdate or Save Changes buttons that PHP kicks in, permanent saves are made to the database and the admin screen refreshes, which it’s why it’s so important to click those buttons.

4. JavaScript and the WP-REST API

Over the past year, JavaScript has graduated from a supporting role to one closer to the lead when it comes to WordPress, and this is all because of the WordPress REST API.

I’m not going to go into huge amounts of detail here on what the API is, as we’ve already done that, but this is one example of how WordPress interacts with JavaScript.

The API itself is written in PHP, as it needs to use a server-side language to interact with the database. But the difference is that you can interact with it using JavaScript, specifically using JSON objects.

I’ll give you an overview of how to do this later in this post, but first I’ll take a look at the place where most people start when it comes to using JavaScript with WordPress: adding it to plugins and themes.

Using JavaScript in Your Plugins and Themes

If you’re adding JavaScript effects, the way to do so is in your plugins and themes. If you’re using the REST API, you can either do this in a plugin or theme (using PHP with optional JavaScript) or via an external application (using JavaScript). In my opinion, it’s worth starting by using jQuery to add an interaction or two, as that will help you to familiarise yourself with using JavaScript. But if you want to go straight to using the REST API, then go ahead!

Let’s take a look at how you insert scripts to your themes and plugins and how you call external libraries.

1. Adding Scripts to Plugins and Themes – the Right Way

If you’ve listened to Matt’s advice and spent the Christmas holidays learning all about JavaScript, you’ve probably come across instructions on how to call scripts from the <head> of your pages. If you’re working with static HTML, this is the correct way to do it.

But stop!

In WordPress, you shouldn’t call scripts from the <head> section, tempted as you may be to add that to your theme’s header.php file or hook it to wp_head in your plugins. There is a correct way of adding scripts in WordPress, which is called enqueueing.

Enqueueing scripts is better for two main reasons:

  • It avoids adding a script more than once, as WordPress won’t load the same script twice if it’s enqueued twice.
  • It manages dependencies and order of adding scripts for you: so if one script (e.g. one you’ve written using jQuery) needs another one (e.g. jQuery) to be loaded, then it will do so in the right order.

Note that jQuery (amongst others) is already enqueued within WordPress, so you don’t need to enqueue it – just enqueue your own scripts and set jQuery as a dependency.

Enqueuing scripts in WordPress - WPMU DEV guide
Learn how to load scripts correctly in WordPress with our guide

To enqueue scripts you use the wp_enqueue_script() function, placing this inside your own function which you then hook to the wp_enqueue_scripts hook. If you want to load a script in the admin screens, you use the wp_enqueue_scripts() function in the same way but hook your function to the admin_enqueue_styles hook.

So to load a script in your theme, you would use this code:

This adds a script called my-script.js, which is stored in the scripts filter in your theme. I always add scripts in a separate folder as it keeps things organized, and is particularly useful if you need to add ore than one script. This script is dependant on jQuery and will be loaded on every page.

Sometimes you might not want to register your script on every page, in which case you use two separate functions: wp_register_script and wp_enqueue_script(). For full details see Daniel Pataki’s tutorial on enqueueing scripts the right way.

2. JavaScript: Some Familiar Concepts

JavaScript and PHP have a common heritage: they’re both descended from the C programming language. This means there are a fair few JavaScript concepts that will be familiar to you if you’ve got experience working with PHP. The not so good news is that there are other concepts which will be completely new to you, and others which are similar to PHP but slightly different (meaning you’ll have to be careful not to write your JavaScript like it’s PHP: a bit like learning Italian was for me after previously learning Spanish!).

Some JavaScript concepts that will be familiar to you if you’re experienced with PHP include:

  • Comments. You use exactly the same syntax to comment out text in JavaScript and PHP. Certainly a bonus for someone like me who keeps trying to use PHP-style commenting in CSS files.
  • Syntax. JavaScript and PHP have a similar syntax, with both using a semicolon at the end of a line. JavaScript differs in the way it uses periods before methods but it uses parentheses and quotation marks in a way which will be familiar.
  • Variables. You can define variables in JavaScript in much the same way as in PHP, with the main difference that you add var before the variable name. You can also use global and local variables in both JavaScript and PHP.
  • Strings, arrays, booleans and numeric values. The way these work and the syntax used for each is very similar in JavaScript and PHP. The main difference is that in JavaScript you use syntax to denote arrays, not the word array.
  • Operators. JavaScript uses the same operators for arithmetic and comparisons (e.g. + and >=), with just one difference: JavaScript has the modulus (%) operator, which returns the remainder of one number divided by another. Both JavaScript and PHP use = for assigning values and == for equals.
  • Functions. You can create functions in JavaScript as you can in PHP. The basic syntax is the same as in PHP.
  • Conditions. You can use if, else and else if in JavaScript in the same way as you would use ifelse and elseif in PHP.

But there are some ways in which JavaScript differs from PHP, and some new concepts. Here are some of the most important:

  • Syntax. JavaScript is more forgiving when it comes to syntax. So if you miss out a semicolon, your code will still work.
  • Methods. A method is something that happens to an object. It’s similar to a function in PHP – when you create a function, you then call it using a method, or you can call a built-in method. You can recognise a method by the brackets that follow its name.
  • Objects. An object in JavaScript is something on the page, such as an element. Variables are also a kind of object. Objects in PHP are very different, and are used in conjunction with classes in object-rented PHP.
  • Properties. Properties are the values associated with an object. Properties are also used in PHP (with classes), but they work differently.

Methods, objects and properties are the core concepts you’ll be using when writing JavaScript. Let’s demonstrate them with an example:

In the code above I’ve created a variable (an object) called animal. That has an array of properties, type and color, each of which has a value. I then use the document.write() method to output the value of the type property to the web page.

3. Using jQuery to Add Effects and Animations

The jQuery library adds to what’s available in JavaScript to give you a vast array of effects you can use in your themes and plugins and comes bundled with WordPress, so it’s a great place to start. It’s also the easiest way to start working with JavaScript: a bonus!

When you’re working with jQuery you’ll be using JavaScript syntax and can continue to use the same objects, properties and methods you would use in vanilla JavaScript, but you can also use the those provided by jQuery.

jQuery Selectors

A powerful aspect of jQuery is in the way it lets you select elements by using their CSS. So for example you would select an element with the id of banner like this:

You could then take that selector and apply a method to it, like so:

This takes the element with the ID of banner and adds a <h1> tag to it with contents, using the append() method.

jQuery Methods

jQuery itself has a number of methods that you can use to create animations and effects. Examples include adding content, dynamically changing css, hiding and deploying elements, making elements move and change size: for a full list, see the jQuery website.

jQuery uses a few simple concepts that you’ll use in your code:

  • selectors: you’ll need to select an element (or multiple elements) on the page so that you can do something with them.
  • filters: you can filter your selection, so that only certain elements are selected (such as odd numbered elements).
  • events: jQuery can react to specific events such as a mouse click or keyboard press. You can combine these with selectors so that something happens when a specific link is clicked, for example.
  • variables: define variables based on selections, inputs or values you define, and then manipulate those variables.
  • effects: once you’ve selected something, or an event has triggered, you can then apply an effect to the element selected. Effects include fading in and out, sliding elements up and down, or toggling between these.
  • animations: using the animate() property, you can animate any CSS property that accepts numeric values, for example text size, position of an element or opacity.

jQuery (or, more correctly, JavaScript) also makes use of functions which you can define, not dissimilarly to how you would in PHP.

And if the jQuery methods and effects aren’t enough for you, then you can use the jQuery UI library, which gives you access to even more interactions and effects.

JavaScript and the WP REST API

Here’s where things get interesting. The WP-REST API lets you do much more than just adding effects using JavaScript: it lets you interact with your site’s database.

It does this using JSON (JavaScript Object Notation). JSON is designed to read, write and edit data using JavaScript. It uses JavaScript concepts I’ve already introduced: objects, arrays, strings and values.

So each entry in your database is an object. It has a label (a string) and a value. Your site will also have data which consists of arrays, and arrays within arrays.

The JSON website
The WP-REST API uses JSON, a JavaScript subset

JSON can handle all of this. Just as in PHP, a value can be a string, a number, an array (here’s where nested arrays come in), or a boolean value. It can also be an object.

Understanding how to use JSON with the REST API in detail is beyond the scope of this post, but here’s an introduction to getting started:

  • Tools. The first thing you’ll need is an HTTP client that will interact with the API. The most popular one I’ve come across is Postman. You then work in this client.
  • Discovery. Before interacting with your site, you’ll need to check whether the site has the REST API enabled. There’s more than one way of doing this, which you can learn about in the REST API documentation.
  • Authentication. For security reasons, you’ll need to use authentication. You can do this using one of three methods: cookie authentication for themes and plugins running on the site; oAuth authentication for external applications; and basic authentication for external clients during development (not recommended for production as it’s less secure). Find out how this works on the REST API site.
  • Fetching data. You do this using the GET command. This fetches all of the data associated with a post but doesn’t output anything. So for example to get all of the posts in a site I would use:
  • Or to get just one post, with the ID of 100, I would use:
  • Editing and posting data. You can do more than just fetch data: the PUT command lets you edit data and the POST command lets you post new data. Think of putting like updating a post and posting like publishing one. To start with I recommend using the API to fetch data, in case you make mistakes and lose your data.
  • Outputting and manipulating data. Once you’ve used the GET command to fetch data, it’s available for you to output and manipulate. The REST API gives you a number of functions you can use to work with and filter JSON objects: one of the most user-friendly resources I’ve found that demonstrates this is Josh Pollock’s ebook on the WP-REST API.

You can either work with your data in a PHP plugin or bypass PHP altogether and create standalone applications using JavaScript, which is where the possibilities really open up. I’d recommend starting with a mix of Javascript and PHP using the tips in Josh’s book or our guide to using the WP-REST API, as the learning curve is less steep.

JavaScript Needn’t Be Scary!

The thought of leaving behind your hard-earned PHP skills and learning JavaScript can be daunting. But the good news is that JavaScript has a lot in common with PHP; not only does it share some common concepts, syntax and code, but it also uses a structure and logic which will be entirely familiar to PHP developers.

JavaScript has become a hot topic in WordPress circles because of the WP-REST API, but it has plenty of other applications within plugins and themes. By learning the JavaScript and jQuery required to add this kind of functionality, you can start to develop your JavaScript skills and then move on to applying these with the REST API, fetching and manipulating JSON objects to create flexible, powerful applications using data stored by WordPress.

Are you learning JavaScript? Have you started working with the WP REST API or Calypso? Let us know your tips for learning JavaScript in the comments below.

Rachel McCollin

Rachel McCollin Rachel is a freelance web designer and writer specializing in mobile and responsive WordPress development. She's the author of four WordPress books, including WordPress Pushing the Limits, published by Wiley.