I’ve been wanting to get more familiar with the JSON API proposed for WordPress core and also with Angular (a javascript framework), so I decided to start building a little web app idea I’ve had for a while.
I’ve started small. My first experiment was just to see if I could connect to the JSON API and output a list of most recent posts. To do this, I built a basic theme with only the essential components: a stylesheet, a functions.php, an index.php, and the custom javascript.
You can find it on GitHub here.
How the JSON Works
Since the JSON API is not in WordPress core yet, you’ll need to install it as a plugin: https://wordpress.org/plugins/json-rest-api.
Once it’s installed, you should be able to access the JSON at:
yoursite.com/wp-json/posts
If it looks like an ugly blob of text, I’d highly recommend installing a browser extension to prettify it. I use the JSONView extension for Chrome.
Enqueue the Scripts
For this really simple theme example, we’ll just need to load a couple scripts and a stylesheet. We’ll load Angular (through the Google CDN) and our custom javascript to display the posts. It’ll should look like this in functions.php:
https://gist.github.com/devinsays/dd557b6cdb807c3efc19
You’ll notice that wp_localize_script is also being used. This is so we can use PHP to output a variable (the path to the JSON API) which our javascript can read.
Custom Javascript
This app.js is about as pared down as I could make it. It defines the api path in the root scope, and then fetches the most recent 10 posts in the controller.
If you view the console log in the browser, you should see correct JSON API path outputted, along with the object of data that is returned.
https://gist.github.com/devinsays/67055f35170385fa4a04
Display Posts
Finally, we need to render these posts on the front end. To do that, we just loop through the returned data in index.php. In this example, I’m just displaying the title and excerpt:
https://gist.github.com/devinsays/f7115d8294d6beed99ff
What’s Next
As you can see, it’s pretty simple to get started with Angular with WordPress. If you want to download this little theme to experiment with, you can download it from GitHub.
For the little app I’m building, I’d like to display a quote when someone visits the site. If they want to see another quote, they’ll click a button. I also want the option for unauthenticated visitors to be able to submit a new quote.
So, as I piece this all together, I’ll try to keep posting my progress.
