End of Year Sale: 30% off your first year on annual plans. Use code AP5-30-OFF See plans
Tutorial

Using the WordPress REST API in a mobile app

Updated 4 min read
JSON REST API (WP API) plugin page
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!

53 responses to “Using the WordPress REST API in a mobile app”

  1. Hadi Avatar

    Surely its great news! Thanks for sharing! 😀

  2. Bronson Quick Avatar

    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! 🙂

    1. Scott Bolinger Avatar

      Hey Bronson, thanks for the comment, I’ll be posting more tutorials in this series for sure!

  3. darrenpinder8 Avatar

    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!

    1. Scott Bolinger Avatar

      Hey Darren, ask and ye shall receive 😉

  4. […] Posted on July 15, 2014 by Scott Bolinger This is part 2 of our series about how to build a mobile app with WordPress and Phonegap using the JSON REST API. You can find part 1 here. […]

  5. Henk Frederique Avatar
    Henk Frederique

    Very nice indeed. However, why didn’t you run into cross-origin problems with those AJAX requests?

    1. Scott Bolinger Avatar

      Hi Henk, Phonegap allows you to whitelist domains, which allows cross-origin requests. For browser testing, Safari works for me, but Chrome does not (not sure why honestly!)

  6. Gastón Coroleu Avatar

    Hi, nice tutorial, one question… why doesnt work posts scroll? or doesnt work only to me?

    1. Scott Bolinger Avatar

      I haven’t tested on multiple devices, there may be a scrolling issue (I’m guessing on Android?) You may have to tweak the CSS.

  7. soufiane Avatar
    soufiane

    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. Scott Bolinger Avatar

      Hi, you can’t use a localhost for the API, it needs to be a live site.

      1. soufiane Avatar
        soufiane

        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!!!!

  8. Francesco Avatar
    Francesco

    Any way to add pagination to posts?

    1. Damien O'Neill Avatar
      Damien O’Neill

      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

  9. Nasse Avatar

    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.

  10. Erkan Avatar

    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.

  11. sahilbmsharma31 Avatar

    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.

    1. Scott Bolinger Avatar

      Hi, the API now supports jsonp, which will solve that problem. You can also view this article for more on cross domain issues: http://torquemag.io/preparing-wordpress-site-power-single-page-web-app/

  12. […] talked about the REST API in other posts, so I won’t go into technical details here. Basically we pull in data like posts and pages […]

  13. sahilbmsharma31 Avatar

    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.

  14. sahilbmsharma31 Avatar

    How to get data in JSONP format using wordpress JSON rest Api. Please suggest.

  15. marklathamukMark Avatar

    Struggling a bit… I have a self holsted WP site that Ive set up and activated the plugin. You can see that page here:

    http://indexserver.co.uk/appcontent/wordpress/

    But when I change the url to see the JSON data I get a 404?

    http://indexserver.co.uk/appcontent/wordpress/wp-json/posts

    1. Andrew J T Avatar

      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.

      1. marklathamukMark Avatar

        Hi Andrew thanks for the reply but I had a deadline with this so I ended up using blogger.com – it has a json output built in 😉 Similar to this plugin probably but no need to install anything, you can see it here:

        http://laney-ironheart.blogspot.co.uk/feeds/posts/default?alt=json-in-script&callback=myFunc

  16. Andrew J T Avatar

    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. Scott Bolinger Avatar

      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.

  17. Yahia Avatar

    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. Scott Bolinger Avatar

      Right, you’ll have to build in load more functionality. If you use a framework, it may already be available. For example, we use the Ionic Framework for Reactor, so we used that to load posts 10 at a time.

  18. Gastón Coroleu Avatar

    Hi, thanks for your tutorial. My app display a list with all post titles with featured image. How i do for when i click in one of this posts open entire post in other page?

    1. Vadim K Avatar
      Vadim K

      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‘ +
      ” +
      ” +
      ” +
      ”;

  19. kingleroyg Avatar

    Hi, Great tut… It works perfectly for me, but It comes back with html tags, how did you remove them ?, or you removed them from a wordpress side

    1. Scott Bolinger Avatar

      HTML tags are part of the api, I don’t think there’s a way to remove them.

  20. ashish jangra Avatar

    To Work On Chrome Just Install This Extension
    Allow-Control-Allow-Origin: *
    It Allow Chrome To Get Ajax Request From Third Party Domain

  21. Zaid Erikat Avatar

    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.

  22. Fabio Avatar

    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

    1. Scott Bolinger Avatar

      Hi, this is not our REST API, it is an open-source project by Ryan McCue and others. It’s possible to add post meta, you should take a look at their documentation: http://wp-api.org/

    2. Jeff Avatar

      Hi Fabio,

      Have you found any info on this subject. I have been racking my brain on this for days…

      Thanks,
      Jeff

      1. Bjorn Avatar

        Hi Jeff, Fabio…you can find details about extending the API and additional post data for JSON REST API on the page called ‘Guides’ on http://wp-api.org/

  23. hskrox Avatar

    Hi mate, thanks alot for this, I am stuck at the beginning of Ajax part. How should I begin with it. Plz help me fast.

  24. Elvin Avatar

    Great tutorial! Any ideas on how to return more custom post types? Default value is 10 posts

  25. Fernando Avatar
    Fernando

    Hello.

    Been trying to use your Github example : https://github.com/scottopolis/wp-rest-api-demo with Version 2 of WP REST API – http://v2.wp-api.org/, but can’t seem to make it work. I changed var rootURL = ‘http://www.mysite.com/wp-json/wp/v2/posts/’; and also url: rootURL + ‘/posts/’, but it does not get anything.

    What am I missing? Thanks.

    1. Scott Bolinger Avatar

      Hi Fernando, it won’t work with v2 of the WP API, they changed a lot of stuff. I’ll try to write a new article on v2 soon.

  26. SA James Avatar
    SA James

    I like this tutorial and i need more. Also please, where can i get buddypress rest api mobile app tutorial like this?

    1. Scott Bolinger Avatar

      There is no BuddyPress REST API, so I don’t think that type of article exists, sorry.

  27. sibu116 Avatar
    sibu116

    Hi, is there a way to allow users to comment on articles within the app? if so, how can this be implemented into the app.

    1. Scott Bolinger Avatar

      Yes this is possible, but it is a bit complex. It requires making your own form in the app, and posting each comment to WordPress through the REST API with authentication.

  28. […] in this article. If you are interested in building your own WordPress- and API-based mobile app, check out AppPresser’s tutorial on the […]

  29. Fahima Avatar

    great tutorial! As a matter of fact,I’m looking to know more about.Thanks 🙂

  30. Fahima Avatar

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

    1. Scott Bolinger Avatar

      Hi, that’s what this article is about. You can also purchase AppPresser, which is easier to use if you don’t want to write custom code, and support most plugins: https://apppresser.com/pricing

  31. Raja Singh Avatar

    very good articles thanks for sharing
    keep up the good work

    1. Cosmic Blocks Avatar

      Nice Tutorial

WordPress

iOS & Android app builder for WordPress

Ready to build your app?

Turn your WordPress site into iOS and Android apps with push notifications on every plan.

AppPresser End of Year Sale: 30% off AppPresser subscriptions, now through Dec 31. Two phones show sample news and events apps built with AppPresser.

End of Year Sale

30% off your first year

On Standard, Professional and Advanced annual plans. Enter the code at checkout. Ends December 31, 2026 at 11:59 PM ET.

Code AP5-30-OFF
See pricing