Last night I attended my local WordPress Meetup with the topic of the WordPress JSON REST API. I was really excited to attend because the whole idea of a REST API is something I know about, I just don’t really know what it does and what the purpose of it is. All that has changed.
Getting Some Closure
My main experience in using a JSON API was my recent work on the Steam Achievements plugin I’ve been working on. Now I see that with the API plugin installed in your WordPress you can connect to the site to perform CRUD operations. JSON is great to work with because its a lot of data in a small package, and it’s a standard for giving and getting data across the internet. Using JSON to communicate to your WordPress site gives you a way to separate the data from the presentation.
This is best understood by a couple examples that were presented. This JSON REST API plugin was developed by the MOMA blog Inside / Out. Their site is presented as a Ruby on Rails front end, but use WordPress as their publishing platform. The use the JSON API in their Ruby Templates that pull the data from the WordPress Database.
Another great point that Vasken mentioned is the JSON end points will still work with cached pages. It will also be backwards compatible when WordPress adds the JSON API to WP Core, which will be happening in the next couple of updates.
There is a Chrome extension called Postman that lets you play around with all of the JSON REST API your site is outputting. You can even do it while running a site on a local server. I just installed it in Chrome and looking forward to seeing what I it can do.
Best Practices Going Forward
He began with some good examples of performance. Reminding us that it in PHP you want to avoid multiple calls to your database. Similarly in JS you want to avoid multiple calls to your DOM. Instead you should save the object that you call into a variable. However with all of these variables being made it can be a problem if you don’t plan your naming and run into name collision.
Prefixing your function names is a good option, but you can do one better in both PHP and in JS. Object Oriented PHP lets us avoid function name collisions with creating a class and instantiating it.
Whenever you have to globalize a variable make sure that it is unique. Don’t get lazy and give yourself problems in the future.
In closing Vasken gave us a few concepts to make sure we left with.
- Consider the WordPress Ecosystem
- Use Closures for your plugins whenever possible
There’s a lot on the horizon, but I’m ready to take it on.