Angular + WordPress JSON API

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:

<?php
/**
* Angular Experiments.
* Enqueue scripts and styles for the front end.
*
* @since 1.0.0
*/
function ae_scripts() {
// Load main stylesheet.
wp_enqueue_style( 'ae-style', get_stylesheet_uri() );
// Load Angular
wp_enqueue_script( 'ae-angular', '//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js', array( ), '', true );
// Load custom app script
wp_enqueue_script( 'ae-js', get_template_directory_uri() . '/js/app.js', array(), '', true );
// Variables for app script
wp_localize_script( 'ae-js', 'aeJS',
array(
'api' => get_bloginfo( 'wpurl' ) . '/wp-json/posts',
)
);
}
add_action( 'wp_enqueue_scripts', 'ae_scripts' );
view raw ae-1-functions.php hosted with ❤ by GitHub

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.

var myapp = angular.module( 'myapp', [] );
// Set the configuration
myapp.run( ['$rootScope', function($rootScope) {
// Variables defined by wp_localize_script
$rootScope.api = aeJS.api;
}]);
// Add a controller
myapp.controller( 'mycontroller', ['$scope', '$http', function( $scope, $http ) {
// Load posts from the WordPress API
$http({
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]' : 10
},
}).
success( function( data, status, headers, config ) {
console.log( $scope.api );
console.log( data );
$scope.posts = data;
}).
error(function(data, status, headers, config) {});
}]);
view raw ae-1-app.js hosted with ❤ by GitHub

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:

<div ng-controller="mycontroller">
<article ng-repeat="post in posts">
<h3>{{ post.title }}</h3>
<p>{{ post.excerpt }}</p>
</article>
</div>
view raw ae-1-index.php hosted with ❤ by GitHub

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.

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

11 Responses

  1. Angular is amazing! Glad to here that you start using it for your apps. We’ve been using it for a while for our Meta Box Builder extension and one of our shortcode plugin. I love the “2-way binding” feature which allows me to add “live preview” to our products!

  2. Hey nice stuff Devin, I’ve been thinking about doing the same with Backbone. Seen a few such examples around recently and wondering why it seems everyone is approaching this with Angular when Backbone and Underscore achieve can the same result, with data binding and front end templates, yet are already in core. You just need to `wp_enqueue_script(‘backbone’);`

  3. Nico

    Hi, great article!

    It would be great to see how we could serialize the output so that it displays correctly on the client side.

    Cheers!!

  4. James

    Great Tutorial Devin, thanks for writing this! I have followed your tutorial and initially it worked as hoped.

    I’m having a bit of a problem when I have a high number of posts (around 160), the performance really drops and it takes around 4-5 seconds to load the data from JSON. Have you encountered this issue as well? I find I have the same problem when loading thumbnail images, text and titles to if I was just loading titles.

    I’m still getting into Angular so any tips would be great! Thanks!

      1. James

        Thanks for the reply Devin! I am loading all at once, I think the best approach would be to load 10 at a time like you suggested. Now to work out how to do that! Thanks mate,

        James

  5. Steve Lombardi

    Nice tutorial. Only issue I have, with latest WP 4.3.1, Angular 1.4 the text is formatted with html tags that are visible (as in some text).

    How can I convert this back to rendered html?

Leave a Reply