Scott
Bolinger
Update 12/7/16: The REST API is now in WordPress core! You don’t currently need a plugin if using 4.7+.

View our updated article for using the final version of the WP-API in a mobile app using Ionic 2 here.

The REST API is currently a plugin that allows applications to access the data produced by WordPress in JSON format. Version 1.0 was recently released, and it is slated to be in WordPress core by version 4.1 later this year.

This is incredible news for anyone interested in making mobile apps with WordPress!

The implications of this API have already been written about by WP Tavern, this article will focus on how to use it to build a mobile application.

Let’s talk about creating a simple mobile app using Phonegap that will pull data from your site using the REST API.

First, either view or download the tutorial files by clicking the link below.

Download tutorial files

Setting things up

The first thing you need to do is install the REST API plugin on your WordPress site.

In my case, I’m running WordPress locally on my Mac, using Desktop Server.

After the REST API plugin is installed and activated, you can visit http://yoursite.com/wp-json to see the basic JSON object. It looks something like this:

{"name":"AppPresser","description":"Just another WordPress site","URL":"http:\/\/www.wp4.dev"}

You can see elements of your site by appending the url, such as http://yoursite.com/wp-json/posts, or http://yoursite.com/wp-json/pages.

That’s the data that we’ll use to pull into the mobile app.

The mobile app

REST API demo mobile app

We are going to make a hybrid mobile app, which is basically a static website that can be wrapped in a native app wrapper with Phonegap.

I won’t go into the details about making this a native app, we’ll just be using a static website for demonstration purposes. Our static website will consist of an index.html file, and some CSS and Javascript files.

You can see the files on github here.

If you look at the index.html file, you’ll see that we have loaded our CSS and Javascript the same way you would on a website, and we also have some basic HTML structure for the header, and post list.

I’m using some pre-made libraries, including jQuery, and Topcoat for the UI.

In the mobile app, all of these assets would be local on the phone, we do not pull them in from the website. The only thing we are getting from the website is the data through the REST API.

Custom post types

The app we are going to make is simply going to display custom post types from WordPress. Later on, we can add page transitions, menus, and even push content from the app to WordPress, but let’s not get ahead of ourselves!

To get custom post types, we can access

http://yoursite.com/wp-json/posts/types

I created a post type called “News” for this app, so I can access the data I need at

/wp-json/posts?type=news

My JSON data for the news CPT looks something like this:

[{"ID":2602,"title":"Travel behemoth Priceline","status":"publish","type":"news","author":{"ID":1,"username":"scottopolis","name":"Scott B","first_name":"Scott","last_name":"Bolinger"...

If you don’t have a custom post type, that’s ok, you can access your posts at http://yoursite.com/wp-json/posts. Go ahead and visit that url to view your JSON data.

That object gives us access to everything we need: title, excerpt, content, featured image, author, etc. We can now pull that data into our app, and display it any way we want.

The AJAX

Now that we have the JSON data ready, and the mobile app ready, all we need to do is pull the data into our app. We will use an AJAX request to do that.

I am going to use some jQuery, so we have loaded the jQuery library in the app already.

The AJAX request looks like this:

$.ajax({
	type: 'GET',
	url: rootURL + '/posts?type=news',
	dataType: 'json',
	success: function(data){
	// do something with the data here
	}
});

That goes and gets the data, and inside the success function is where we’ll loop through and display it.

In this case we will use $.each to get the items we want from each news article, and add those into a list item. The HTML will look like this:

<li class="topcoat-list__item">
<img src="http://url.com/featured/image.png" /><br>
<h3>Title</h3>
<p>Post excerpt</p>
</li>

We’ll need to get the featured image url, the title, and excerpt through the API. The code for that will go in the AJAX success function, and it looks like this:

$.each(data, function(index, value) {

  $('ul.topcoat-list').append('<li class="topcoat-list__item">' +
  	'<img src="'+value.featured_image.attachment_meta.sizes.medium.url+'" /><br>' +
  	'<h3>'+value.title+'</h3>' +
  	'<p>'+value.excerpt+'</p></li>');

});

You’ll see that I’m drilling down into the featured_image object to retrieve the medium image url. If you don’t do that, you’ll get the original file, which might be too big.

You can see the full code for the AJAX on Github.

Wrapping things up

You can load the index.html file into Safari to see how the app is looking so far. (Chrome blocks the AJAX request)

You could wrap this app with Phonegap and load it into a simulator if you wanted, but there’s a lot more we can do with it first.

We can add menus, page transitions, local storage, posting data TO WordPress, and much more. If you are interested in learning how to do more with this type of app, let me know in the comments.

Cheers!

Everything you need to know about AppPresser in 4 days

Ios-android-hero-300

Learn how AppPresser works, and how it can help you get a great mobile app published quickly and affordably. Get 1 email each day for 4 days.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit

51 thoughts on “Using the WordPress REST API in a mobile app

  1. Hey Scott, I’d definitely be interested in learning how to do more with the app! I’m keen to learn how to add a menu and page transitions and I’d love to see you add push notifications using AppPresser and AppPush for it too. I’ve been having fun playing around with WP-API but I haven’t done much app development yet. Hopefully you post a few more tutes and your code. Thanks for sharing! 馃檪

  2. Great tutorial! I had no idea JSON REST API even existed before reading this, now I’m very excited about what it might mean!

    I’d love to read more about how to use menus, page transitions, posting data to WordPress, etc., so please do write more!

  3. Hey Scott,i want to thank you for this great work!!!!!
    I have a question: i use my wordpress site in loclahost and i want to know what i should modify tu get my content
    Your help would be much appreciated.

      1. But The JSON content shows up.And i have the same problem when i try to run the application with your URL
        thanks for your help!!!!

    1. Hi Francesco.

      This is not something that is currently a feature of AppPresser, however, we are looking at adding it in a future release. Stay tuned!

      Damien

  4. Great tutorial! Any ideas on how to return more custom post types? Default value is 10 and adding ‘&count=’ doesn’t seem to do the trick.

  5. hey, i do exactly the steps but if I open http://localhost/index.html with safari so i see only the a gree page with the titel My App and left the Menu Button. No think else.

    i edited app.js

    var rootURL = ‘http://www.mysite.de/wp-json’;
    url: rootURL + ‘/posts’,

    what can be the problem? thanks.

  6. Hey, I am having cross domain issue on browser and i din’t test it on ipad yet. But when i put both website and app in same domain it works.

    Please help me in solving cross domain issue for IOS Application. Not able to show data from JSON format.

  7. I don’t know about jsonp, i am using the latest version of json rest api plugin. In the article that you have suggested, it suggest to add_filter code. But can you please suggest me where to add this code.

    I am struggling with CORS issue since two days. Please suggest something very effective.

    1. try going to Settings -> Permnalinks and click “Save Changes”, that is what solved my issue, also, you may want to try it out on an install with no plugins activated and the latest default wp theme, this is what I had to do to figure out the issues/conflicts.

  8. nice write-up, I have been scouring the web for info on wp-api – one thing I can not seem to find an answer to is
    How do you restrict access to /wp-json/posts – I understand that you need authentication for creating posts and whatnot, but how can you make it so that authentication is required for every request so that outsiders can not grab content?

    1. Hi Andrew, the API is public, just like your website content. It’s possible to require authentication for stuff like post meta, but I’m not sure how you would completely lock down the api, that’s not really what it’s made for.

  9. Hi, Thanks alot,
    One question, how to do pagination or infinite scroll for the posts page! now I must wait to load or posts, then all posts show up in one time.. is there a trick to make them load like 10 by 10!
    I dont want the user to wait that much till load all the posts!

    1. Hi! I’d worked around this and fixed it. Here is my code from app.js :

      getSinglePost: function(postID) {
      console.log(‘getSinglePost’);

      var rootURL = ‘http://misanec.ru/wp-json’;

      $.ajax({
      type: ‘GET’,
      url: rootURL + ‘/posts/’ + postID,
      dataType: ‘json’,
      success: function(data){
      console.log(data);
      $(‘.single-post .image’).attr({src: data.featured_image.attachment_meta.sizes.medium.url});
      $(‘.single-post .title’).append(data.title);
      $(‘.single-post .content’).append(data.content);

      },
      error: function(error){
      console.log(error);
      }

      });

      },

      and

      var singlePost =
      ” +
      Back‘ +
      ” +
      ” +
      ” +
      ”;

  10. Hay, Thank you for this great tutorial, but i have a proplime there is no data showing and in the Console i keep getting this:
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [MY WEBSITE URL]wp-json/posts?type=post. This can be fixed by moving the resource to the same domain or enabling CORS.

    I searched for answer but nothing works, i’m getting data from website to show it on my localhost.
    Please Help.

  11. Hi Scott,

    thank you for your great work. Before trying the plugin I need an info: I am in the need to add posts from the mobile and I have seen that the plugin is capable of this with a REST call. But my posts have few custome fields (made with ACF plugin). Is your RestAPI able to add custom fields too?
    Thanks

    Fabio

  12. Hey Scott,I’ve got one more question,how to make a wordpress website which can communicate with a mobile app ?(android,iOS)

Leave a Reply

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