Using the WordPress JSON API with Angular js


For my website, I wanted to use Angular JS. To keep things easily manageable though, I wanted to use WordPress to store my project details & blog posts. This meant I faced the problem of pulling out WordPress posts and fetching them with an Angular service.

Step 1 – Install JSON REST API for WordPress

Fortunately, this process was made a lot easier by using the WordPress plugin JSON REST API.

JSON REST API is very easy to set up. All you need to do is find it in the WordPress plugin directory, install it, and then the plugin takes care of the rest. You can then query the WordPress database with a new REST interface, making it very simple to get the data within an Angular application. It also gives you access to the common WordPress query filters, such as filtering by category name, or choosing how many posts you want to fetch.


Step 2 – Set up an Angular service


angular.module('WordpressService', []).factory('Wordpress', function($http) {

	return {

		getPortfolio: function() {
			return $http.get('http://yourdomain.com/wp-json/posts?filter[category_name]=projects&filter[posts_per_page]=-1');
		}

	}

});


Step 3 – Call the service in your controller

How you handle the data is really up to you from now, but as you’ll see from above, we are return the $http.get() function to the controller, which is a Promise. Here’s an example controller, which I have injected the service ‘WordPress’ into:


angular.module('PortfolioController', []).controller('PortfolioController', function($scope, WordPress) {

	Wordpress.getPortfolio().success(function(projects) {
		$scope.portfolioProjects = projects;
	});	

});


Step 4 – Use the data in your template


<article ng-repeat="project in portfolioProjects">
	<h2 ng-bind-html="project.title"></h2>
	<div ng-bind-html="project.content"></div>
</article>

Notice how I have used the ng-bind-html=”” attribute. This makes sure that Angular will render HTML tags and characters such as the ampersand (&). To use this, you will also need to include ngSanitize in your project.


Conclusion

No doubt I could go into a lot more detail with this tutorial, but this should help to get you started on the road to using a WordPress JSON API alongside your Angular application. Try taking the basic example I have provided and building on top of it and integrating it cleanly into your code.


Leave a Reply

Your email address will not be published. Required fields are marked *