Getting Started with Block Themes: Patterns

Block Patterns, or simply patterns, enable theme developers to create custom blocks that are compositions of blocks provided by the standard block library, and if desired, with additional design flourishes. For example, Twenty Twenty One includes support for blocks designed with overlapping images and text, among others. In the blocks version of Twenty Twenty One, these will be registered as patterns within the theme.

Repeatable design patterns

Unlike templates, patterns are defined in PHP in a way that might be more familiar to experienced theme developers. We can define them in the functions.php file of our theme, or a file that is included there.

First up, as a matter of good practice, we register a category for our patterns using the register_block_pattern_category function. By categorising our patterns, we can separate them from other patterns such as those registered by WordPress core, and other third-party plugins:

register_block_pattern_category(
    'theme_blocks',
        array( 'label' => esc_html__( 'Theme Blocks', 'theme-blocks' ) )
);

Now we can start adding our patterns with the `register_block_pattern` function. The parameters for this function are the pattern name as a string, and an array of properties to be associated with the pattern. This array comprises a title, content, description, categories, keywords and viewport width. Putting this together, a simple pattern can be registered like this:

register_block_pattern(
    'theme-blocks/pattern-name',
        array(
            'title'         => esc_html__( 'Pattern Title', 'theme-blocks' ),
                'categories'    => array( 'theme-blocks' ),
                'viewportWidth' => 1024,
                'description'   => esc_html_x( 'A description of what is in the pattern', 'Block pattern description', 'theme-blocks' ),
                'content'       => '<!-- wp:columns ... -->'
        )
);

Most of what we’re doing here is self-explanatory, however the content property may look less familiar. This property contains the raw HTML content for the pattern. What we add here follows the same convention as template parts.

Getting real

It’s easier to think about what this contains if we work with a real pattern, so let’s take Twenty Twenty One’s Overlapping Images pattern. The content looks like this:

<!-- wp:columns {"verticalAlignment":"center","align":"wide","className":"is-style-twentytwentyone-columns-overlap"} -->
    <div class="wp-block-columns alignwide are-vertically-aligned-center is-style-twentytwentyone-columns-overlap">
            <!-- wp:column {"verticalAlignment":"center"} -->
                <div class="wp-block-column is-vertically-aligned-center">
                            <!-- wp:image {"align":"full","sizeSlug":"full"} -->
                                    <figure class="wp-block-image alignfull size-full">
                                            <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/roses-tremieres-hollyhocks-1884.jpg" alt="' . esc_attr__( '“Roses Tremieres” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                        </figure>
                                <!-- /wp:image -->
                                <!-- wp:spacer -->
                                    <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
                                <!-- /wp:spacer -->
                                <!-- wp:image {"align":"full","sizeSlug":"full"} -->
                                    <figure class="wp-block-image alignfull size-full">
                                            <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/in-the-bois-de-boulogne.jpg" alt="' . esc_attr__( '“In the Bois de Boulogne” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                        </figure>
                                <!-- /wp:image -->
                        </div>
                <!-- /wp:column -->
                <!-- wp:column {"verticalAlignment":"center"} -->
                    <div class="wp-block-column is-vertically-aligned-center">
                            <!-- wp:spacer -->
                            <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
                            <!-- /wp:spacer -->
                            <!-- wp:image {"align":"full",sizeSlug":"full"} -->
                                <figure class="wp-block-image alignfull size-full">
                                        <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/young-woman-in-mauve.jpg" alt="' . esc_attr__( '“Young Woman in Mauve” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                    </figure>
                            <!-- /wp:image -->
                    </div>
            <!-- /wp:column -->
    </div>
<!-- /wp:columns -->

To ease readability, we have added line breaks and indentation, but it’s worth noting that as this is ultimately just a string, when we come to registering our pattern, we can paste it in as a long line of text.

What we can see in this block is a mix of regular HTML, with the Block Editor’s pseudo HTML expressed as comments. Boiling it down, this markup contains two columns, with each one containing an image and some stylistic spacing. The images used here are just placeholders that can be modified by users in the editor, but it’s worth noting that any placeholder images used in a pattern must also be included in the theme assets.

You may note that in the markup above, it’s not entirely clear where the magic that makes these columns overlap occurs. This is achieved via a block style, and applied using the is-style-twentytwentyone-columns-overlap class.

Putting it all together

With all of this in place, here’s how we can now interact with our pattern in the site editor.

As you can see, we can find it by searching for “overlap” in the block editor. We can also browse all of our patterns in the block browser which is accessed by clicking “browse all” when selecting a block in the inline editor.

Why should I use patterns?

Hopefully this has helped you gain some understanding of what patterns are and how they work. Don’t worry if you’re still a little confused. There’s a lot to take in here and it’s something that makes more sense once you start making patterns. However, you may still be wondering why we’re talking about this and what the advantages are of using patterns.

Patterns are very helpful when users are trying to create more advanced layouts that have a greater sense of art direction than WordPress has traditionally provided. They’re a great way of breaking the monotony that can set in with long-form content, as well as helping users break the sense of creative block that is often felt when confronted with a blank page. As you can see in the patterns included with Twenty Twenty One, users have easy access to more versatile and visually interesting ways of presenting their content.

Next steps

To help consolidate your understanding, check out the full implementation of Twenty Twenty One’s patterns in the experimental block-based version of the theme.

Challenges in JavaScript-Based Theming

Welcome to part three of our tutorial on building themes with JavaScript. In part one we considered the JavaScript web landscape and where it leaves us today. In part two we looked at the forthcoming WordPress REST API. In part three, we will consider the most pertinent question: how do we apply all this to WordPress theming? Some of you are likely already realizing that there are surely a lot of challenges in doing so. And you would be right.

Watch the video presentation or read the transcript below.

Demo Materials

You’ll find accompanying material for this screencast available in a public GitHub repo — each screencast has a corresponding folder with a very simple theme that can be activated.

Getting Real

As you may have noticed in the previous tutorial’s files, we need a theme skeleton to make a project like this work. Fortunately, WordPress only requires themes to have a style.css and index.php file to be recognized. Beyond these two files, we can build the whole thing in JavaScript. If this thought is setting off alarm bells for you right now, I understand. Put those alarm bells to one side for just a little while.

If we are going to build a theme with JavaScript, we probably don’t just want one massive JavaScript file. We also don’t want to have to enqueue lots of separate JavaScript files just for the sake of keeping things tidy. Fortunately, others have already done this work for us. CommonJS — a project which, like Node.js, kicked off in 2009 — has created a myriad of specifications and conventions for JavaScript developers to follow; they’re a bit like a JavaScript version of the W3C. The CommonJS project has created specifications for JavaScript modules, which we can use to split up our code. JavaScript modules allow us to create something similar to a WordPress theme, with different JavaScript files containing different template parts and theme files.

Although we can split out our code into different JavaScript files as we can with PHP, unlike with PHP, we’ll want to concatenate these files into one when we run the theme. In theory, we don’t have to do this — but if we don’t, each page would need to enqueue lots of different JavaScript files, which is bad for performance and user experience.

To concatenate the files we’ll will need to use a build tool, such as CodeKit, Grunt, or Gulp. We can even use Unix’s Make utility, which was first released in 1977(!), to run our build process. At this stage, it doesn’t really matter, as the main thing our build process will do is smoosh our JavaScript files into one file, so whichever utility you’re most comfortable with is fine. For this tutorial, I’ll use my current favourite, Webpack.

Let’s take a look at how these JavaScript modules work. In part two, I showed an example of a very basic JavaScript theme with some inline JavaScript. We were breaking quite a few WordPress conventions, with everything in one big index.php file.

I’ve now broken this up and turned it into a more conventional theme. In index.php we now just get a header and footer. We’re now enqueueing our JavaScript in our functions.php file correctly. And our JavaScript file now sits on its own.

But if you look closely, you might notice something has changed. Our changePost function has disappeared, and instead we are requiring the changePost function. If we go back to the containing directory, you can see that we also have a changepost.js file. This file now contains the changePost function. Note that at the bottom, we have a line that says module.exports = changePost. This is the CommonJS convention for defining what the module actually is. So when we require it, this ensures that what we require is the changePost function itself.

Let’s get concatenating. I’ve mentioned that we’re using Webpack, so let’s get that set up. First, you need to install Node.js. Fortunately, this is a lot easier than it used to be — simply go to nodejs.org and download the automatic installer for your system. Once node.js is installed, we can run a command to install Webpack:

npm install webpack -g

This gives us global command-line access to Webpack. With this done, we can now run the most basic Webpack command, which is to take a source file, and smoosh it into a compiled file. The command for this is:

webpack ./theme.js compiled.js

We can now view the compiled file and see that it contains the contents of both changepost.js and theme.js. An extra little bonus with Webpack is the -p flag, which simply means that you want to minify the file – remove whitespace and remove all comments etc. You can see that even this simple example our compiled file is almost a third of the size it was unminified.

We can also add the -w flag which means we want Webpack to watch the files and automatically recompile whenever we change anything.

With the file compiled, we can see everything in action working together.

The Route of All Evil

With everything we’ve looked at so far, you can probably imagine stringing together a theme that allows a user to browse through different chunks of content from their website. However, a major missing piece is routing, something that you may not have heard of. Routing broadly encompasses the way that we deal with URLs changing. Let’s say a user visits our site, clicks to a different post and wants to share the link. With the examples we’ve looked at so far, this isn’t possible. Routing also ties into our user’s history. If we have no routes, the user can’t press the back button. No routing also means we have little chance of anything meaningful being indexed by search engines. I’m sure you can now appreciate that routing is very important.

In PHP, WordPress deals with this for us. There is a rather large class called WP_Rewrite (you can find it in wp-includes/rewrite.php). This handles every different type of URL and works out what should be shown to the user. In JavaScript, we don’t have this luxury, so we have to deal with it ourselves.

Let’s look at something basic we can implement.

If you look closely at changepost.js, you’ll notice that I’ve added a new line since the last tutorial. As well as editing the document on success, I’ve added a line that redefines window.location.hash. This is the most basic way of changing our user’s route. You’ve probably seen this used on other websites and it amounts to the same thing as using an anchor link to take the user to certain heading on a page.

Let’s look at this in action. Our eventListener has been added to the first link in the menu. If we click it, note that the route now changes.

So with some very basic routing, we now want to change what happens if the user clicks back.

If we go back to theme.js, the eagle-eyed among you may have noticed another line beneath my link listener:

window.onhashchange = changeRoute

We’re hooking a new function, changeRoute, onto window.onhashchange. Every time the URL changes, the browser fires a hashchange event, so this method allows us to tag our own JavaScript on to what happens when the hash changes. You can see beneath this I have a changeRoute function. Here, we say if the hash equals nothing — as in, we’re on the homepage — show the original post that we fetched in the first place. The code here is almost identical to changePost, but it just gets the original post.

What About no-js?

A few minutes back I mentioned that you might have alarm bells ringing. We’ve now likely dealt with a couple of those alarm bells. But we’re not done. Some of you may be thinking, “But what if the user doesn’t have JavaScript enabled? Or what if something has caused JavaScript to break?” In our current scenario, our website simply wouldn’t work.

There are some who don’t think this is a problem. Today, only a tiny number of people browse the web with JavaScript turned off, and for the most part they’re probably power users who fully understand why they have it turned off and know that it will limit their experience. But I am personally not convinced that we should just forget about no-js situations.

Will Somebody Please Think About the Search Engines?!

Even if we sort out our routing, what about search engines? As it happens, Google is now able to render JavaScript. I’m not sure if it’s official yet, but I’ve experimented with this. For example, the ThemeConf website has no server-side rendering, but try Googling “ThemeConf”. It also works on DuckDuckGo. Despite this, it’s not a great idea to rely on others to render your JavaScript — there are also places where this doesn’t work. Ironically, even though Facebook developed React, it doesn’t render JavaScript-rendered content when you’re embedding a link, for example. To see this in action, and if you use Facebook, try pasting a link to ThemeConf.com there. You don’t have to actually share it of course, but you should notice that the preview of the content Facebook will embed is blank.

I believe the most compelling reason to not rely on JavaScript rendering is performance. A developer at Google called Jake Archibald has given some great talks on this. In a worst-case scenario, our current theme makes our users wait for three page loads when they first arrive. First, the page loads, then the JavaScript loads, then the JavaScript loads the content from the REST API. Yuck! This may not be a problem if you’re connected with fiber-optic broadband, but if you’re on a mobile device or a spotty Wifi connection, you’ll really feel the pain.

This ties back into the search engine point, since we know that Google does take page-load times into account when ranking sites in search results. We really don’t want our load times to be three to four times longer than they need to be.

One way to tackle this problem with our simple theme example would be to add PHP to render the theme as well. In our simple example, this wouldn’t take too long and will work fine. The content would load exactly as the menu and footer loads, then the JavaScript will load and take over. However, this would very quickly get out of hand if we tried to build a whole theme. We would be forever having to repeat ourselves, and generally getting into a massive tangle.

Already, our simple JavaScript theme is starting to get pretty messy!

In the next part of this tutorial, we’ll look at how to move from our basic theme to something more advanced, building from an altogether more stable foundation.

The Series

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

Introducing REST APIs

Welcome back to our tutorial on building themes with JavaScript. In part one, we considered the JavaScript web landscape and looked at where we are today. I suggested that while JavaScript lets us render content in new and interesting ways, there are challenges when it comes to fetching the content in the first place.

Watch the video presentation or read the written transcript below.

Screencast

Demo Materials

You’ll find accompanying material for this screencast available in a public GitHub repo — each screencast has a corresponding folder with very simple theme that can be activated.

Time for a REST

With traditional WordPress themes, we’ve been able to use all manner of loops and custom queries to get data. In shifting our approach to be less PHP-centric, where will our data come from?

The missing piece of our puzzle is a REST API, essentially an HTTP interface for getting data from a source. The REST part stands for REpresentational State Transfer. Think of it as a way of accessing WordPress queries directly through a URL. We can type a URL into our browser and include parameters just like we would with a custom loop, and in the browser we can see pure data from our website.

A REST API also allows you to post data, so the WordPress REST API allows you to add and update content directly without using the admin interface. Certain types of requests do need authentication, the REST API only publicly exposes content which is already revealed by WordPress through other avenues, like RSS feeds.

This all means that you don’t have to worry about connecting to a database, you just use a series of URLs to access different types of content on your site — these are known as endpoints.

The WordPress REST API is due to be fully incorporated in WordPress 4.5, due in the spring of next year. In fact, the infrastructure of the WordPress REST API will be included with WordPress 4.4 and has already been merged into trunk.

Exploring the WordPress REST API

Next, let’s look at some of the basic things we can do with the WordPress REST API.

I have a WordPress environment set up locally where I have installed WP API. Ahead of its inclusion in core, WP API is available as a plugin on the WordPress plugin repository. With the plugin activated, I can navigate to the URL /wp-json/. At this URL I can see an overview of everything that the REST API makes available to me.

Screen Shot 2015-11-25 at 17.39.08

As the URL suggests, WP API uses JSON formatted data. This is not compulsory for REST APIs, but most REST APIs will use either JSON or XML formatted data. More recently JSON is the preferred format as it’s less verbose and generally easier to work with. I’m also using a Chrome extension called JSON View, which adds sane line breaks and some colours to make it easier to read the JSON. Without JSON View, the JSON data is quite hard for a human to read!

The REST API adds namespaces to its endpoints. This is to ensure that extensions and future versions of the API don’t break functionality for sites and software that use it. The primary namespace at the moment is wp/v2. This means that we can build our website against version 2 of the REST API. If, in the future, it’s decided that the REST API should be structured differently, this restructure would happen under the namespace of wp/v3. Therefore the REST API could completely change, but what we built for v2 would be safe with the inherent backwards compatibility of the v2 namespace.

So, if we navigate to /wp-json/wp/v2/ we can see all of the information about this namespace. As newcomers, we don’t have to worry about this at the moment, but it’s worth understanding the path we take to what we’re really trying to get from the REST API.

If we add posts/ to the end of the above URL, we finally start seeing the data from our website. By default, posts/ will show us the same content that a generic loop on our homepage would. On a clean install of WordPress, this is usually the 10 most recent posts.

Screen Shot 2015-11-25 at 17.39.35

We can further narrow down our request to the REST API by adding a post’s ID to the URL. So in this instance, /wp-json/wp/v2/posts/1241/ will show us just the one post with ID 1241.

The REST API provides typical things that we might want in relation to a post. We can see the date, modified date, permalink, title, content, excerpt, format, whether or not it’s sticky, and more.

Now let’s consider an example where we use the REST API to render content on a page using JavaScript.

I’ve set up a basic HTML document set up in my text editor, including a div with the id "page", an anchor link with text “Hello world,” and an empty h1 and div element. The div has an id of "content".

Beneath that, we have some inline JavaScript inside a script tag. To begin, we use JavaScript’s native XMLHttpRequest API to fetch our data. This is what’s behind jQuery’s Ajax functions, you may remember this from part 1 when I spoke about the website YouMightNotNeedjQuery.com.

What this does is fetch the URL from the REST API that we were just looking at. If it’s successful, it will parse the JSON response so that we can access the different elements as a JavaScript object. We then use the querySelector and innerHTML methods to change the data in the HTML on this page. At the moment we aren’t dealing with errors, we would want to deal with these if we were doing this in production.

Let’s see how this works. If I activate the session 2 theme on my test site, we can see what this does. There we go, the data from the REST API is being rendered in my theme demo.

One last thing before we end this tutorial. We still have that link that I added at the top — let’s look at how this is connected.

Well, if we go back to the index of our little theme and scroll down, you can see we also have a function, changePost. This does exactly the same thing as the other bit of JavaScript, but it gets a different post (with ID 1). Beneath this, you can see that we add an event listener to the link. The link listens for a click, if it gets clicked it fires the function. Let’s see what happens.

There we have it.

You can now see how a very basic WordPress REST API-based theme can work. In the next screencast we will consider more advanced approaches to theming and the challenges we face when taking this approach.

The Series

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

The ThemeShaper JavaScript Theme Tutorial

Dive into the brave new world of JavaScript WordPress theming, looking at best practices and pitfalls along the way.

Introduction

WordPress theming hasn’t changed very much over the past few years. It’s certainly become more refined, and projects such as Underscores (_s) have helped promote best practices and robust standards. That said, we can still go as far back as Kubrick and find plenty of common ground with the most recent WordPress themes.

This isn’t a bad thing, and it’s probably one of the reasons WordPress is so popular and so many people have been able to get involved in theming. But the web has changed substantially since WordPress welcomed its first default theme in 2006. More than half the web’s users now access it from mobile devices. We have HTML5, and with it a whole host of browser APIs that didn’t exist in 2006. These advances have helped a whole new ecosystem of JavaScript-based web apps blossom.

Some aspects of this ecosystem have found their way into WordPress themes. Most of us have probably seen our fair share of jQuery-enabled carousels. We have JavaScript-enhanced tiled galleries and lightboxes available through plugins like Jetpack. Yet very few of us would consider building a theme entirely in JavaScript. The thought may even send shivers down many of our spines.

Building a WordPress theme with JavaScript might be considered lunacy by some, who may wonder why you’d want to attempt such a thing. Others may have questions about SEO, performance, accessibility, plugin compatibility, among a myriad of issues. There are definitely challenges to building a theme with JavaScript, and before reading any further you should know that this is still an experimental area of WordPress theme development.

But, and this is a big “but,” a JavaScript-based approach to theme-building opens up a wonderful world of new possibilities to the curious developer, including:

  • Storing and pre-fetching content using the browser’s Web Storage API to allow server-less, seamless transitions — using the browser’s History API — between posts and pages.
  • Animations within themes, for more natural and intuitive interactions.
  • The ability to create entirely offline experiences using all new Service Workers.

Along with these exciting improvements, the WordPress REST API is being integrated into Core. The REST API makes it much easier for us to build themes with JavaScript. There is no better time to start getting familiar with how the WordPress ecosystem is changing.

The Series

In this five-part tutorial, we’ll expose you to the brave new world that WordPress theme development might inhabit in the coming years. While the best practices for building a theme in this way are still to be established, we’ll do our very best to guide you into the secret garden of the future.

Stay tuned for:

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

JavaScript, jQuery and the Web Landscape Today

This is the first in our five-part series on building WordPress themes with JavaScript. Let’s kick things off with an overview of today’s web landscape and how JavaScript fits in. The vast majority of WordPress themes today use jQuery for at least something, so I’ll look at how we’re building themes today, and how we can think about using JavaScript techniques that may be less familiar.

Check out the video presentation or the written transcript below.

Screencast

A Brief History of JavaScript

What is JavaScript? In Douglas Crockford’s JavaScript: The Good Parts he describes JavaScript as the language of the browser. It enables developers to manipulate the web browser, and therefore affect users’ interactions with the browser. This is at the core of why we should even be thinking about JavaScript in the context of theming.

I’m not just talking about the DOM (Document Object Model). Of course, without JavaScript we can control what the user sees in the browser. But with JavaScript, we can interact with things beyond the DOM. We can edit the browser’s history, we can store data in the browser’s memory, and now we can even create push notifications. This takes us even further than the browser and into the user’s device.

For a long time, JavaScript also allowed us to do things asynchronously, loading things in the background while the user is doing something else. Google, via Gmail, have been doing this since 2004. At that point, working with JavaScript was prohibitively difficult, and unless you had a lot of developers and money, you didn’t generally use it in the way Google did. That said, developers did start making basic use of the Ajax techniques that Google largely pioneered with Gmail. Ajax stands for Asynchronous JavaScript and XML.

Getting Our Hands Dirty

Let’s look at some simple things we can do with JavaScript in Chrome’s developer console, using the BBC website as an example. (All modern browsers have an equivalent way of doing this.) I’m not going to use jQuery, just so we can get more comfortable with the idea of pure JavaScript.

First, we want to select something in the DOM. The two most common methods for doing this are getElementById and querySelector. They’re similar, except with querySelector we can select elements by their class. As its name suggests getElementById only allows us to select elements by their ID.

With something selected, we could now change pretty much anything about it. This is basically what jQuery does behind the scenes.

jQuery etc.

I’ve mentioned jQuery a few times. Years ago, many felt JavaScript was arcane and hard to understand. There were a lot of browser inconsistencies and compatibility issues. The jQuery project, which kicked off in 2006, tried to abstract the difficult problems with JavaScript, and allow people to more easily make use of it. At its essence, jQuery is a library of abbreviations. A great introduction to jQuery is the website YouMightNotNeedjQuery.com.

When this site first went live it was the butt of a lot of jokes, but it’s actually quite a useful resource. On the one hand we can see how jQuery really does shorten how much code we need to write, but sometimes the jQuery version is no shorter than pure JavaScript. Occasionally, the jQuery way is even slightly longer, such as with outerHTML.

I’ve used jQuery a lot in my time as a developer and while it can be useful, I do believe that jQuery can restrict those using it to what it is able to do. I also think that because of jQuery, a lot of developers remain mostly unfamiliar with JavaScript itself.

It’s also worth noting that there are/were some other players in the same field as jQuery, for example MooTools and YUI.

A Whole New Node

In 2009, JavaScript saw the start of a bit of a renaissance, as Node.js landed, which allowed you to run a server with JavaScript. The JavaScript renaissance really hit its stride in 2011 with the arrival of npm, the Node Package Manager. This was huge because it made it trivial to create and distribute JavaScript modules. In a way, npm is like a JavaScript version of the WordPress plugin repository. Since Node’s arrival, lots of new JavaScript libraries and frameworks have come onto the scene including Backbone, Ember, Angular, and React.

These new libraries and frameworks have made it easier for developers to create quite impressive app-like websites with JavaScript. At the same time, many of the browser inconsistencies and compatibility issues with JavaScript have been ironed out. We are now in a position with JavaScript where we can take pretty much complete control of the user’s experience on our websites. The one missing piece of the puzzle in the context of WordPress is data. Yes, we can manipulate the DOM and move things around, but how do we get the data from WordPress? That’s where the REST API comes in, and that’s what I’ll be focusing on in the second part of this tutorial.

The Series

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

Theming with the REST API – Meet Picard

If there’s one thing that has been making waves in the WordPress ecosystem this year, it is the new REST API. Officially known as WP-API, and currently available as a plugin, it is due to be rolled into core at some point this year.

A REST API?

A REST API may not initially seem like a useful feature for theme developers. It is clearly very useful for those looking to use WordPress as an application platform, but how the REST API can be used within a theme is perhaps more opaque.

The Theme Division at Automattic have had an eye on the potential uses of a REST API powering a theme for at least a couple of years now, and in recent months some concepts have started to take shape.

The Future is JavaScript

There are many potential benefits to building themes that rely more than ever before on JavaScript and the REST API, including but not limited to:

  • Design: We can have smooth transitions between the different types of content on our websites.
  • Speed: We can store content from the REST API in localStorage (effectively the browser’s memory). This means that on the initial site load we can store any post that is retrieved. Imagine a user clicking a ‘read more’ link and the full post being displayed without the need of a further server request.
  • Offline: By handling interactions with JavaScript, as developers we gain control of what happens if the user goes offline while browsing our site. We can let them know that the server doesn’t appear to be reachable and we can present content that we know is stored in their browser in a graceful way.

Picard Screenshot

Picard

In February of this year, the team worked together on a prototype REST API theme that has become known as Picard (a geeky nod to “the next generation” of themes). To create Picard, we used React, a JavaScript library for building user interfaces. Coupled with vanilla JavaScript and a number of other libraries sourced through npm, we were quickly able to produce an engaging, working prototype.

Recently, I have been talking about building themes with the REST API and our approach to building Picard at a number of WordCamps so far this year, culminating in a workshop at the inaugural LoopConf.

Today, Picard is now publicly available on GitHub.

Tango

We intend to continue developing Picard and working on some of the harder problems that we have not yet solved. We aren’t stopping at Picard either. Our experiments have led us in various directions. My colleague Kirk Wight has created another experimental theme called Tango. Tango is an extension of the concepts we are exploring with Picard, blended with the bulletproof Underscores starter theme.

Make It So

The future of WordPress theming may dramatically shift with the official adoption of the REST API but you don’t have to wait for the future to take advantage of it now. Clone Picard and Tango. Experiment and see what you can do. These are exciting times for themes!

Further Reading and Resources


 

Photo credit: JD Hancock/flickr