Using AngularJS and JSON API to retrieve WordPress content

AngularJS removes the boundaries a standard html website had and opens up a wide range of opportunities making it easier and faster to build dynamic web applications. Marrying it with WordPress and its REST API makes perfect sense whether you want to utilize existing contend within your application, dynamically pull data from various websites or build a dynamic AJAX-driven WordPress theme.

The purpose of this tutorial is to analyze the process behind requesting and importing WordPress posts. The same method could easily be used to retrieve a wider array of details such as comments, categories or users.

Set up files and dependencies

Let’s start by creating our index.html file.

I included the most up-to-date versions of angular.js and angular-route.js. Because of the way AngularJS is decoupled we have to include the routing module separately.

I also added Bootstrap so we don’t have to worry about CSS during this tutorial.

Let’s include the app.js file where we’ll be hosting our core functions.

We start by adding a new module with a funky 'angular♥wp' name and we’re injecting the 'ngRoute' dependency. At this stage Angular is not working yet. We should modify the index.html file so our app knows where it should be initiated. Let’s add the app name to the html tag. We should also add the ng-view element to indicate where the content will be placed in our document.

Configure Routing

Now that we have our core files in place we can start writing the application. The first step is to configure the routing. That’s what we needed the 'ngRoute' module for.

We added 2 new components. In the first one: $locationProvider, we’re telling our app to enable html5 mode. Among other things it enables our app to manage the browser’s address bar. Without it the URL would include an additional /#/.

In $routeProvider.when we’re telling the app to load a template part from content.html file when we’re on the root page ('/'). Let’s create the content.html document then.

We should also add the Main controller that’s been mentioned in the app.js.

The app should place a short message in the console to confirm that it’s working correctly so far.

Getting WordPress posts using JSON

To be able to access WordPress posts we have make sure the WordPress site returns them in a JSON format. There are few ways to achieve that.

Jetpack

We could use the highly popular Jetpack plugin which now includes the JSON API. Simply install the plugin, activate it, authorize it using your WordPress account credentials and enable the JSON API module in Jetpack Settings.

In this case we would ask the WordPress site to provide the JSON data. We would use the following query: 'https://public-api.wordpress.com/rest/v1.1/sites/' + siteDomain + '/posts/'. The siteDomain is the URL of the site we want to pull content from so in my case it will be 'amielucha.com'.

Please note that the object returned by Jetpack is slightly different from the object returned by WP REST API v2.0 therefore some variables would have to be modified. For the purpose of this tutorial I’m going to show only the structure of the WP REST API.

WordPress REST API plugin

For the purpose of this tutorial I’m going to use the most recent beta version of the REST API plugin. When using this plugin make sure the site’s permalinks are properly configured.

In this case the JSON results URL will be [SITE_URL]/wp-json/wp/v2/posts/. If you access it directly you’ll see the unformatted JSON structure. To format the JSON object in Chrome browser you could try this Chrome extension.

json-formatted-unformatted

Back to our app.js

Now we can finally request the JSON content from our WordPress blog and return the object in the browser’s console. We saved the results in $scope.posts so it can be later accessed by our AngularJS app.

Now that we have the data, all we have to do is display it on the screen. We’ll use the content.html file for that purpose.

We’re using Angular’s ng-repeat to loop through all elements in $scope.posts. Then we’re displaying each post’s title and the excerpt.

If you run the app now you might notice that it’s not returning the correct html. In order to achieve that we’ll use the $sce service component.

$sce service component

Note: As of AngularJS 1.3 the ngBindHtmlUnsafe has been removed and replaced by ngBindHtml.

To enable ngBindHtml let’s inject $sce into our Main controller as a dependency. Then we have to iterate through all the untrusted html in $scope.posts and convert it to a trusted form.

We should also modify content.html to bind the trusted content using ng-bind-html attribute.

Now that we are able to see the proper html content we could experiment with pulling different kinds of information. To see a full list of queries you can use refer to the WP REST API documentation. The most commonly used paths include /wp-json/wp/v2/pages /wp-json/wp/v2/comments /wp-json/wp/v2/users /wp-json/wp/v2/taxonomies or /wp-json/wp/v2/types.


This article is based on Eric Wolfe’s presentation during yesteryear’s WordCamp and Yoren Chang’s post.

11 responses to “Using AngularJS and JSON API to retrieve WordPress content”

    • Thanks Tarciso. That’s a valid point. I’m planning to follow up with an article explaining alternative approaches and I’ll consider this solution.

  1. This tutorial looks great but I’m relatively new to WordPress and I can’t figure out where these files need to be? Are they inside the WordPress folder?

    • Thanks Cort. The purpose of this tutorial is to show how to include WordPress posts on a non-WordPress site, therefore you would create those files outside of your WordPress installation. The only thing you should set up on your WordPress site is the REST plugin.

  2. I understand you ‘love’ the possibility letting AngularJS client talk with a WP back end. I also do! Putting the heart symbol in a html string as you do I can live with. Using that in your code is VERY bad programming style. Use it in your own code if you like but don’t propagate it in tutorials please.

    • Hi Violacase. Could you expand on the subject and explain the dangers of using the ♥ character in AngularJS module name? If there is a vulnerability or incompatibility that this practice could cause, I am more than happy to update the article with the findings.
      I do not encourage using non-standard HTML entities everywhere throughout the code, but inserting a lighthearted detail in demo code shouldn’t cause a stir. For me it increases visual discoverability of a string within the document, especially when a modified portion of code appears in several instances.

      • I took some time to find some good explanations for this issue for you on the web. After grabbing some good links I noticed your comments section on this site was gone…

  3. You should double check the functionality of your code before publishing. (And triple check when your code is supposed to be tutorial)

    The function in apps.js:
    $http.get( api.query ).success(function(res)

    is lacking:

    $scope.posts = res;

  4. I tried the codes on my wordpress multi site, found that returned 404 error in my console, so that the recent posts didn’t show up. Anyone facing the same issue, please try this code: to fix that error. Works fine on my system 🙂

  5. Great tutorial! I have a question, i got to your website by searching for an issue related to json data created by WP API 2. I can see that some fields like title, guid, content etc have rendered: key inside them, can you tell me is this a wordpress update or something else. I never noticed this before maybe because i was using wordpress get_title etc. Why is it added as i see no point?

Leave a Reply