Developing A Theme for WordPress Using ReactJS, Redux, and the WP REST API

To being, check out the project here.

This is a work in progress, but I got enough done this weekend that I’d like to share.

I wanted to work on a project using ReactJS and Redux. I’ve heard a lot about it, and wanted to explore it on my own. I do that with every technology before I bring it to the office. Since WordPress incorporated the WP REST API in the core for version 4.7 I though that that might be a great opportunity to explore both the API using ReactJS+Redux.

There were a number of interesting challenges I faced building this. The idea was to make a theme that would work 100% like any other WordPress theme; that could be installed and work normally.

As it currently stands there are some missing features, which I’ll get to later. But this is past a proof-of-concept and well along the path to be fully operational.

I will explain more about how it all fits together in a future post, maybe when I load it onto this site. In this post I just wanted to muse about the process so far, and invite others to join in the project or share their ideas and implementations.

Endpoints: Handling Pretty Permalinks

The first challenge was to figure out how to handle “Pretty Permalinks.” You know what they are. Back in the early days of CMSs all URLs ran off of GET variables (http://blog.example.com?p=23). But because Google gave better SEO juice to readable URLs we all started getting urls that were readable. This was incorporated into WordPress as well.

The problem with implementing this in a single-page JS app is that the default path for posts is  /year/month/name-of-post/. That can make routing complicated. Not only that, but you can change the permalink format too. So in order for this theme to work, I’d have to handle that.

My solution was to have a catchall route and build a custom endpoint for Pretty Permalinks that would be powered by the url_to_postid() method. This ended up working pretty well and is what powers both single pages and posts.

Endpoints: Menus

Another challenge was how to handle menus. They’re dynamic, and not included in the current API. To solve this I borrowed the main class from the WP API Menus plugin. (I love GPL, don’t you?) It was written by Fulvio Notarstefano, and was beautifully implemented.

I contemplated having the menu data loaded as js variables on page load, since they don’t change. But I wanted the challenge of figuring out how to implement multiple versions of the same element with ReactJS+Redux, so they got their own endpoint.

Endpoints: Featured Images

I also modified the main post endpoint to include featured images so that I wouldn’t have to do a separate call for each image on archive pages.

Search

Another challenge, in general, was handling the different routes for different actions. It’s not all that complicated once you get the hang of it. But working in single page apps can get interesting, and if you’re not careful you can lose the benefits of using frameworks like Redux.

All in all the WP REST API is quite robust and is now polished. If you check out my redux actions you can see that I’m using the same endpoint for the main index archive, single posts and search. Which is really nice. I’ll be expanding this file for the taxonomies as well. Apparently all you need is to add a filter GET variable.

What’s still missing from the project?

There’s still a lot to do. First and foremost, there is currently only minimal styling.

There are a whole lot of things that are needed to make it a theme the might be accepted into the theme repo. First of all, I haven’t done anything with taxonomies yet.

I’d also like to add widgets. That is another interesting problem which I’ll probably solve the same way I did pretty permalinks — add a new endpoint just for them. I’ll have to render them completely on the server, then pass them down via the API. It’s not pretty, but it should work.

I’ll also want to clean up the hooks that run before the page loads. Since the entire theme is running off the API, directly from the index.php, it won’t need a lot of the server-side processing, as that is done already in the API.

The customizer isn’t playing well with the menus, I’ll have to figure that out.

I’m sure there’s a whole bunch more that needs to be done too. I’ll write about what I discover in the summary post once (if) this theme goes live.

Closing thoughts

It’s a fun project and I’ll look forward to playing more with ReactJS and Redux. The first thing I noticed was how snappy it was. It also forces you to think about the different components in a very healthy way. When designing components, each one should be independent. You should be able to drop any one in any other project (for the most part) and use it with minimal wiring up. That’s good coding practices.

Join me!

If you find this project interesting please feel free to share with me your ideas for it.

How to use JSONP (AJAX to SSL) in WordPress, an EASIER way

I’ve already written about How to use JSONP in WordPress Development. I explain how it works, and why you would use it there.

At work we work with several domains and I’ve had to use quite a bit of JSONP, I’ve rethought how to use it, and made this micro-framework to make it a LOT easier. Mostly, I wrote this to solve the problem that I’m using a lot of AJAX, and don’t want the overhead of the .ajax call each time.

There are a lot of values you need to set when making a JSONP call in general, and specifically with WordPress, this greases those wheels.

The paradigm is all you do is execute:

wp_jsonp("wp_jsonp", "getStuff", {variable: "hello world"}, getStuff);

and the rest is taken care of on the JS side. I wrote it to be agnostic of the server-side processing as well, this gives you the benefit of a pseudo factory design pattern with your switch statement.

You can download the whole repo to peruse or play with if you like, I made some gists for easy embedding.

This is the guts of the operation, I created this javascript object that handles everything, you past the ajax event, method, parameters and a callback function. The plugin takes care of the nitty gritty details that are a pain to remember for getting jsonp to work.

It’s well commented, so read through and feel free to ask questions in the comments if you have any.

Here’s the example, you might say, wait a minute, don’t you get a callback from jQuery already? Sure, good luck using it. It’s a little funny ignoring that, but hey, this works nicely.

Maybe I’m overthinking / over-complicating things, I don’t know, once it’s set up you can move really quickly, isn’t that the point of a framework?

Just one important note: make sure to validate the hell out of things because you’re giving that JS function a LOT of power.

I’d love to hear your thoughts, if you have suggestions for improving it, by all means, please comment below!

How to use JSONP in WordPress Development. The Quick-and-Dirty QuickStart Guide

Edit: Looking for an easier way to do JSONP in WordPress?

What IS JSONP and why should I care?

There’s been a lot of debate lately about whether to move your site to SLL (https) or not. It’s clear, though, that all your forms, at least the ones that handle sensitive data like logins, should go over a secure connection.

If your whole site is SSL then you won’t have any issues with making AJAX calls; however, if you DO go hybrid then Javascript will consider all the pages that are SSL as a separate domain and will block AJAX calls to them.

Use case: You want to secure your admin area and you add define(‘FORCE_SSL_ADMIN’, true) to your wp-config.php file. You’ll remember that to make AJAX calls in WordPress you need to call: “/wp-admin/admin-ajax.php.” But that will now be an SSL connection and violates Javascript’s “same-origin policy“.

This is where JSONP comes into the picture. As you probably know, you CAN include scripts from other sites using a script tag, that ability is the foundation of CDNs. JSONP takes advantage of that functionality.

Basically, instead of including a static script on your site hosted on a  CDN, you’re sending a GET request to the domain of choice, and asking it to send back a callback method including within it a JSON object with the data you want. In essence, you’re spoofing your browser to think that it’s not actually doing a cross-domain ajax call, but in practice, you are.

There’s a great discussion on StackOverflow about JSONP for further exploration.

How do I do it?

Below you’ll find two files, upload them to a folder in your WordPress plugins directory and activate. Note: you should probably run this on a test site. It won’t do anything bad to your site, but it’s never a good idea to play around on your production site.

To test it add the following to any page:

[prettify] [/prettify]

The javascript looks for an input button, on ANY page of your site, with the name “titleSubmit” and does the JSONP call with the content of an input text field on that page with the name of “title”.

The code.

The most important pieces in the example that you’ll need to get your code running are:

In the js file:

Clearly without any of the code it won’t work properly; however, the above settings are not typical of most of your standard AJAX calls.

type: GET: By it’s very nature a JSONP call cannot be POST. You’re essentially embedding a script tag on your page with GET variables in the URL of the script.

cache: false: Removing this will not break your code, but for testing it’s best if you your browser doesn’t cache the responses.

dataType: “jsonp”: You’re telling jQuery that it’s a JSONP call. Duh.

crossDomain: true: Perhaps with the dataType set to JSONP you’d think the that this would be enabled, that’s the whole point, but you still need to set this.

In the PHP file:

content-type: text/javascript: You’re setting the response type being sent, application/javascript will work as well.

access-control-allow-origin: *: This is another security check, you need to enable any origin for JSONP to work.

$_GET[‘callback’]: Without the callback wrapping your JSON response jQuery will not recognize this as a valid response. It is set in place as a security measure similar to NONCEs.

Conclusion

Once you have the right recipe, JSONP with WordPress is not all that difficult. Use it well.

As always, questions? comments? Don’t hesitate to do so below.

How to Use AJAX in WordPress Development. The Quick-and-Dirty QuickStart Guide

Edit: Enjoyed this? Check out my new post on AJAX using JSONP in WordPress.


There are some great posts and a fantastic wiki page explaining how to use AJAX in WordPress. But I haven’t found a quick plug-and-play tutorial. So here goes…

The problem: A simple form that will give the visitor an input and when they click “Next” it will send the content of the input to the server who will send all the $_POST fields back as JSON. Why you’d want this? Who knows. But it’s a simple problem to solve that you can adopt to do anything.

Here’s the Gist

The code.

This is the plug-and-play version my friends. (Extra points if you recognize what ui framework is here… DON’T JUDGE ME IT’S ONLY FOR WIREFRAMING.)

How to use the code

  • Add include_once('inputtitle_submit_inc.php'); in functions.php. Make sure inputtitle_submit_inc.php in in your template folder.
  • page-ajax_input.php is a template page, make sure it’s in in your template folder. Just create a page in WordPress using “Input Submition Page”.
  • inputtitle_submit.js should be in a folder named ‘js’ in your template folder. Otherwise

wp_enqueue_script( 'inputtitle_submit', get_template_directory_uri() . '/js/inputtitle_submit.js', array( 'jquery' ));

will fail.

How it works

page-ajax_input.php

This is a simple template file. The important elements here are the input field and the next button. They are hooked in the JS file.

inputtitle_submit_inc.php

The server-side magic.

The first line enqueues the js file and pops some variables in for the AJAX onto the page. They are called in inputtitle_submit_scripts().

The next two lines enable the AJAX to work. They create the ajax action “ajax-inputtitleSubmit”. If you only have “wp_ajax_ajax-inputtitleSubmit” it will only work for logged in users. If you only have “wp_ajax_nopriv_ajax-inputtitleSubmit” it will only work for logged out users. If you do this, make sure you have serious security in place.

Those two lines tie the action to myajax_inputtitleSubmit_func(). This is what happens server side. Inside you’ll find some nonce magic for security. The function checks the nonce, then converts the $_POST variables to JSON and sends them back to the browser. Don’t forget the exit();

inputtitle_submit.js

The Javascript.

First I encapsulate the JQuery so that it won’t conflict with anything. Then when the DOM is ready…

When “Next” is clicked it sends a POST AJAX request to the server. The AJAX URL was defined in wp_localize_script in inputtitle_submit_inc.php as well as the nonce.

We send the action, the nonce and the inputted “title” as variables to the server. Then in outputs the response (all $_POST variables as JSON) in the console.

Summary

I built this for reference sake. If you can suggest any best practices or improvements please comment below.