Wordpress and Ionic Integration using Wordpress REST API

Dayana Jabif
Learn Ionic Framework
9 min readJun 10, 2018

--

Create a mobile app for your Wordpress blog in a few hours following this Ionic Framework tutorial.

Do you want to access your WordPress site’s data through a mobile app? Then this tutorial is for you!

This step by step ionic tutorial will show you how to connect your ionic app with Wordpress REST API in order to be able to pull your site’s data. We will show you how to allow users to create new comments and how to authenticate them using JWT (Json Web Tokens).

In this ionic tutorial, we will walk you through the process of creating an Ionic 3 app that pulls in WordPress posts and other content using the WP REST API.

You can download the source code of this Ionic Tutorial in https://ionicthemes.com/tutorials/about/ionic-wordpress-integration by clicking the GET THE CODE button.

We will discuss the implementation of the following features:

  • Show all published posts
  • Show all the information of a specific post
  • Show the comments and categories related to a post
  • Query posts by category
  • Authentication to your Wordpress site using JWT

Without further ado, this is what you are going to build in this tutorial:

Wordpress REST API

The REST API is included in the Wordpress Core from WordPress 4.7! Plugins are no longer required, just install the latest version of WordPress and you’re ready to go.

In order to check that you are able to make requests to the Wordpress REST API you only need to make a request to the following url: http://YOUR-WORDPRESS-SITE/wp-json/wp/v2/ and you should see something like this.

Please note that you need to replace ‘YOUR-WORDPRESS-SITE’ with your own value.

https://ionicthemes.com/ion2fullapp-full-ionic2-app-template-elite-version

What is Wordpress REST API?

The WordPress REST API provides API endpoints for WordPress data types that allow developers to interact with sites remotely by sending and receiving JSON. This enables developers to create, read and update WordPress content from client-side JavaScript or from external applications.

If you are new to WP REST API, I would suggest you to go through the Key Concepts.

Get Wordpress posts inside your ionic app

We are ready to start pulling data from your wordpress site into your ionic app! We will start requesting a list of your recent posts.

In order to get a list of your recent posts you have to make an http request to the following endpoint: http://YOUR-WORDPRESS-SITE/wp-json/wp/v2/posts. This will return a json with the 10 latest posts of your blog.

Going to our ionic app example code, we created a service where we implemented the following function to get your wordpress recent posts. categoryId is an options parameter that you can use if you want to get the posts from a specific category.

Please note that ‘WORDPRESS_REST_API_URL’ is a constant with the value of our WP API url.

getRecentPosts(categoryId:number, page:number = 1) {
//if we want to query posts by category
let category_url = categoryId? ("&categories=" + categoryId): "";

return this.http.get(
Config.WORDPRESS_REST_API_URL
+ 'posts?page=' + page
+ category_url)
.map(res => res.json());
}

The getRecentPosts() function will return an observable with the first 10 posts that match the previous query.

In our home.ts we have subscribe for the observable result in order to get the posts data. Then just iterate the result data and your posts will be there.

this.wordpressService.getRecentPosts(this.categoryId)
.subscribe(data => {
for(let post of data){
//do something with your posts
}
});

For this example we created a list with some information about the recent posts such as title, content, published date and a link to read the full post. In order to display this data we added the following code in home.html

<ion-card *ngFor="let post of posts" >
<ion-card-content >
<ion-card-title [innerHTML]="post.title.rendered"></ion-card-title>
<p [innerHTML]="post.excerpt.rendered"></p>
</ion-card-content>
<ion-row no-padding>
<ion-col>
<button ion-button clear small color="primary" icon-start>
<p class="date">{{item.date.split('T')[0]}} </p>
</button>
</ion-col>
<ion-col text-right>
<button ion-button small color="primary" (click)="postTapped($event, post)" icon-start>
Read More
</button>
</ion-col>
</ion-row>
</ion-card>

Show posts with Infinite scroll

In order to improve our ionic app performance we added pagination to this wordpress example. We decided to implement pagination using infinit scroll.

I don’t like to make this medium post super long, so if you want to implement infinite scroll please check the original post.

Get post information

When we tap on “READ MORE” from a specific post, we want to show all the details on another ionic app page. In order to achieve this, we have to pass as a parameter the post object to this new page, so in our home.ts we create the following function.

postTapped(event, post) {
this.navCtrl.push(PostPage, {
item: post
});
}

Wordpress Post Details

We will create a new ionic page in our app with the following wordpress post data:

  • Post Author
  • Post Content
  • Post Title
  • Post Categories
  • List of Post Comments
https://ionicthemes.com/products

The new page is post.ts where we added the following code in order to get and display the complete post:

ionViewWillEnter(){
this.morePagesAvailable = true;
let loading = this.loadingCtrl.create();

loading.present();

this.post = this.navParams.get('item');

Observable.forkJoin(
this.getAuthorData(),
this.getCategories(),
this.getComments())
.subscribe(data => {
this.user = data[0].name;
this.categories = data[1];
this.comments = data[2];
loading.dismiss();
});
}

getAuthorData(){
return this.wordpressService.getAuthor(this.post.author);
}

getCategories(){
return this.wordpressService.getPostCategories(this.post);
}

getComments(){
return this.wordpressService.getComments(this.post.id);
}

The wordpress REST API requires us to make different API calls in order to get the authors data, the post categories and the post comments. That’s why on the previous code you can see that we have one observable per API call. All this observables are wrapped inside a forkJoin, this means that we will wait till all of them are resolved in order to continue. This is because we want to wait for all the data to be ready before displaying anything.

For the post comments list we implemented infinite scrolling. Its implementation is analogic to the implementation already explained on the previous section.

If you are looking for a super polished user interface and you want to save time by getting a ready made Ionic 3 starter app with Wordpress Integration and many other features you should definitely check Ion2FullApp ELITE.

The Ionic Wordpress integration you will find in Ion2FullApp ELITE has: Recent posts, list of categories and a feed with their posts, custom pages, authentication using JWT (Json Web Tokens). The code is super clean and well structured and it also includes a detailed documentation so you will have everything you need to create your Ionic Woprdress App.

Some screens of Wordpress integration inside Ion2FullApp ELITE

Learn more in https://ionicthemes.com/product/ion2fullapp-full-ionic2-app-template-elite-version

Get Wordpress posts by Category

On this Ionic wordpress tutorial we also included the example of how to get the wordpress posts of a specific category.

When you click on one category label as shown on the screenshot below, we fire the following function.

Post Categories
goToCategoryPosts(categoryId, categoryTitle){
this.navCtrl.push(HomePage, {
id: categoryId,
title: categoryTitle
})
}

The previous function navigates to the HomePage with the selected post category ID. Once in the HomePage, the getRecentPosts() function will be excecuted with the category ID as a parameter. This will bring the latest posts from this category, then everything is similar to step 1.

Wordpress Authentication

If you want to allow your users to insert comments on your posts, then you have implement Wordpress authentication. I have to admit that this can be a bit tricky to implement because it has some sort of advanced configurations. We did our best to explain the required steps in this tutorial.

For Wordpress authentication we are going to use wp-api-jwt-auth plugin which allows us to generate an authentication token. Follow very carefully all the instructions of the plugin documentation and pay special attention when it comes to editing your wordpress .htaccess file.

JSON Web Token (JWT)

JSON Web Token (JWT) is an open standard that defines rules in order to transmit information as a JSON object securely. The information involved is digitally signed which means it can be verified and trusted. For more information check the JWT documentation.

Wordpress Login

For login implementation we are going to use the following endpoints:

  • /wp-json/jwt-auth/v1/token
  • /wp-json/jwt-auth/v1/token/validate

The first one validates the username and password, and if the credentials are OK it will return our authentication token.

The second one validates that a specific token haven’t expired yet.

To enable a user to login to our ionic framework app with their Wordpress credentials, first we need to authenticate it, and then save the users data and token on the Native Storage (so we can retrieve it later).

We created an AuthenticationService where we put all the functions related to Wordpress Authentication. There you will find the following function which tries to authenticate a user:

doLogin(username, password){
return this.http.post(Config.WORDPRESS_URL + 'wp-json/jwt-auth/v1/token',{
username: username,
password: password
})
}

When our ionic framework application starts we check if there is already a logged in user and in that case we will validate if its token is still valid.

To achieve this we will go to our app.component.ts and check if there is a logged user, and in that case we will validate its token. If the token is still valid, we will navigate to the HomePage but if it is expired we will navigate to the LoginPage and ask the user to log in again.

platform.ready().then(() => {
authenticationService.getUser()
.then(
data => {
authenticationService.validateAuthToken(data.token)
.subscribe(
res => this.rootPage = HomePage,
err => this.rootPage = LoginPage
)
},
err => this.rootPage = LoginPage
);
});

Then in our AuthenticationService we have the function to validate the Auth Token.

Please note that we send the token as a parameter on the url and not on the body.

validateAuthToken(token){
let header : Headers = new Headers();
header.append('Authorization','Basic ' + token);
return this.http.post(Config.WORDPRESS_URL + 'wp-json/jwt-auth/v1/token/validate?token=' + token,
{}, {headers: header})
}

Make a comment in a post

To make a comment in a Wordpress post from our Ionic mobile app, a user must be logged in, it means that on the request we have to send the user authentication token. As mentioned on the previous step, we saved the token on the Native Storage, so we only need to retrieve it from there and then call the correct WP REST API endpoint.

I don’t like to make this medium post super long, so if you want to implement infinite scroll please check the original post.

Wow, this was a super complete Ionic Wordpress Integration Post! If you have any comment/question feel free to post it below.

Remember you can download the source code of this Ionic Tutorial in https://ionicthemes.com/tutorials/about/ionic-wordpress-integration by clicking the GET THE CODE button.

If you want to read more tutorials about Ionic Framework visit our official blog:

In IonicThemes we also sell premium ionic templates that you may find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch.

Why don’t you give a chance to this Ionic template and apply this new knowledge?

Enjoyed reading this Ionic Tutorial?

Subscribe to keep learning Ionic! You will receive offers, new ionic tutorials and free code examples from IonicThemes.

Originally published at ionicthemes.com.

--

--

Dayana Jabif
Learn Ionic Framework

Driven by living a free & happy life. I create #angular & #ionic resources to help devs build better apps faster 🚀. Founder of @ionicthemes & @ng_templates