Using the WordPress REST API in a mobile app
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.
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
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
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 =>
Surely its great news! Thanks for sharing! 😀
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! 🙂
Hey Bronson, thanks for the comment, I’ll be posting more tutorials in this series for sure!
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!
Hey Darren, ask and ye shall receive 😉
[…] 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. […]
Very nice indeed. However, why didn’t you run into cross-origin problems with those AJAX requests?
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!)
Hi, nice tutorial, one question… why doesnt work posts scroll? or doesnt work only to me?
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.
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.
Hi, you can’t use a localhost for the API, it needs to be a live site.
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!!!!
Any way to add pagination to posts?
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
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.
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.
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.
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/
[…] 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 […]
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.
How to get data in JSONP format using wordpress JSON rest Api. Please suggest.
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
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.
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
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?
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.
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!
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.
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?
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‘ +
” +
” +
” +
”;
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
HTML tags are part of the api, I don’t think there’s a way to remove them.
To Work On Chrome Just Install This Extension
Allow-Control-Allow-Origin: *
It Allow Chrome To Get Ajax Request From Third Party Domain
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.
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
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/
Hi Fabio,
Have you found any info on this subject. I have been racking my brain on this for days…
Thanks,
Jeff
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/
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.
Great tutorial! Any ideas on how to return more custom post types? Default value is 10 posts
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.
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.
I like this tutorial and i need more. Also please, where can i get buddypress rest api mobile app tutorial like this?
There is no BuddyPress REST API, so I don’t think that type of article exists, sorry.
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.
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.
[…] in this article. If you are interested in building your own WordPress- and API-based mobile app, check out AppPresser’s tutorial on the […]
great tutorial! As a matter of fact,I’m looking to know more about.Thanks 🙂
Hey Scott,I’ve got one more question,how to make a wordpress website which can communicate with a mobile app ?(android,iOS)
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
very good articles thanks for sharing
keep up the good work
Nice Tutorial