Using the WordPress REST API in a mobile app

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!

Ionic + WordPress

2000px ionic logo.svg

Want to integrate WordPress with your Ionic app? We have the tools you need for login, camera, WP-API, and more. Get the plugins and code samples you need.

Enter your name and email if you're interested in learning more =>

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

53 Comments

  1. Hadi on July 8, 2014 at 2:56 pm

    Surely its great news! Thanks for sharing! 馃榾

  2. Bronson Quick on July 8, 2014 at 7:47 pm

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

    • Scott Bolinger on July 9, 2014 at 1:50 pm

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

  3. darrenpinder8 on July 9, 2014 at 4:58 am

    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!

  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 on August 1, 2014 at 8:24 pm

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

    • Scott Bolinger on August 4, 2014 at 1:57 pm

      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 on August 31, 2014 at 4:53 pm

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

    • Scott Bolinger on September 2, 2014 at 11:21 am

      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 on September 2, 2014 at 8:11 am

    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.

    • Scott Bolinger on September 2, 2014 at 11:22 am

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

      • soufiane on September 2, 2014 at 11:50 am

        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 on September 27, 2014 at 11:55 am

    Any way to add pagination to posts?

    • Damien O'Neill on September 29, 2014 at 10:20 am

      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 on October 13, 2014 at 4:19 am

    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 on October 13, 2014 at 4:47 pm

    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 on November 5, 2014 at 1:10 am

    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.

  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 on November 5, 2014 at 11:48 pm

    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 on November 6, 2014 at 12:07 am

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

  15. marklathamukMark on November 20, 2014 at 8:14 am

    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

    • Andrew J T on December 1, 2014 at 12:43 pm

      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.

  16. Andrew J T on December 1, 2014 at 12:40 pm

    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?

    • Scott Bolinger on December 1, 2014 at 6:17 pm

      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 on December 12, 2014 at 5:14 pm

    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!

    • Scott Bolinger on December 12, 2014 at 5:18 pm

      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 on January 14, 2015 at 3:08 pm

    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?

    • Vadim K on April 25, 2015 at 3:18 pm

      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 on January 21, 2015 at 2:02 am

    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

    • Scott Bolinger on January 21, 2015 at 2:04 pm

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

  20. ashish jangra on January 26, 2015 at 4:58 am

    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 on February 13, 2015 at 9:29 am

    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 on February 24, 2015 at 3:58 am

    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

    • Scott Bolinger on February 24, 2015 at 2:25 pm

      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/

    • Jeff on March 7, 2015 at 12:56 pm

      Hi Fabio,

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

      Thanks,
      Jeff

      • Bjorn on July 7, 2015 at 7:49 am

        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 on February 26, 2015 at 9:05 am

    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 on July 14, 2015 at 11:26 am

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

  25. Fernando on September 5, 2015 at 4:06 am

    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.

    • Scott Bolinger on September 6, 2015 at 8:27 am

      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 on November 24, 2015 at 1:51 am

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

    • Scott Bolinger on November 24, 2015 at 8:17 am

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

  27. sibu116 on December 28, 2015 at 11:56 pm

    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.

    • Scott Bolinger on December 30, 2015 at 8:00 am

      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鈥檚 tutorial聽on the […]

  29. Fahima on August 13, 2016 at 8:32 am

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

  30. Fahima on August 13, 2016 at 8:37 am

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

    • Scott Bolinger on August 15, 2016 at 9:17 am

      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 on September 21, 2017 at 6:32 am

    very good articles thanks for sharing
    keep up the good work

Leave a Comment





Scott Bolinger