Using AngularJS with a WordPress backend

Thanks to the WordPress JSON API plugin it’s really easy to make a WordPress theme using AngularJS, or use WordPress as a backend for your AngularJS application. In this post I’ll describe how to create a basic theme from scratch and fetch posts using AngularJS and the JSON API plugin. In order to follow this tutorial it’s useful to have some basic knowlegde about WordPress theme development and AngularJS.

1. Setup WordPress and a new theme

  1. Install the JSON API plugin in WordPress
  2. Access the JSON API settings; activate the Core controller and setup an API address (e.g. ‘api’). You can test if it works by clicking the ‘info’ method of the Core controller. The result is something like: {"status":"ok","json_api_version":"1.1.1","controllers":["core"]}
  3. Now we need to create a new theme. In the wp-content folder create a new folder (e.g. mytheme), and create the following files
    • app.js
    • footer.php
    • functions.php
    • header.php
    • index.php
    • style.css
  4. Add the following code to style.css so WordPress will recognize it as a theme:
  5. Although the other files are still empty we can now activate the theme in WordPress under Appearance > Themes.

2. Enqueue scripts in the theme

WordPress has a very easy way of loading resource files (e.g. scripts, CSS) in the current theme. Open functions.php and add the following code:

As you can see the scripts are first registered, then inserted into the theme and finally we use the wp_localize_script function to include data in a JavaScript format in the page.

3. Setup the theme

In the previous step all preparations been made to load Angular in our theme. Since our header.php, footer.php and index.php are still empty nothing happens yet. Open the header.php file and add the following code:

footer.php:

index.php:

Note I already add some Angular directives in the code. As you can see the Angular application will be named ‘myapp’, and I’m using a controller named ‘mycontroller’.

Now open the website in a browser and take a look at the HTML source. As you can see our enqueued scripts are loaded.

4. Create the AngularJS application

Open the app.js file and add the following code:

Make sure you have some posts stored in WordPress. When you run the website you’ll see a list containing the post titles.

Conclusion

This tutorial was a pretty basic example of WordPress with an AngularJS front-end. The API plugin enables you to fetch posts and even post data to WordPress. When things become too complex for the default API it’s very easy to create your own API functions, see the JSON API documentation.

Further reading

Leave a Reply

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