Ionic Wordpress Integration

Many people asked for a Wordpress Integration Ionic Tutorial, so here it is, enjoy it :)


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.


Without further ado, this is what you are going to build!


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

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.

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>

Infinite scroll implementation:

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

To add infinite scroll to our ionic app we need to add the following code in your home.html file just after </ion-card>.


<ion-infinite-scroll [enabled]="morePagesAvailable" (ionInfinite)="doInfinite($event)">
  <ion-infinite-scroll-content
  loadingSpinner="bubbles"
  loadingText="Loading more posts ...">
  </ion-infinite-scroll-content>
</ion-infinite-scroll>

The next step is to initialize the morePagesAvailable variable on true when the page loads.


ionViewDidEnter() {
	this.morePagesAvailable = true;
}

Now we can focus on the doInfinite($event) function. Wordpress API gets 10 post per page for default when we call /posts endpoint, so in order to calculate the actual page we have to load, we are going to use the following operation:

let page = (Math.ceil(this.items.length/10)) + 1;

Math.ceil(this.items.length/10) is the actual page, and to get the next one we have to add + 1.


Note: You have to substitute 10 for your amount of posts per page you selected. For more information about arguments see this link.


Now the complete function will be like this:


doInfinite(infiniteScroll) {
  let page = (Math.ceil(this.posts.length/10)) + 1;
  let loading = true;

  this.wordpressService.getRecentPosts(this.categoryId, page)
  .subscribe(data => {
    for(let post of data){
      if(!loading){
        infiniteScroll.complete();
        }
      post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
      this.posts.push(post);
      loading = false;
      }
    }, err => {
    this.morePagesAvailable = false;
    })
  }

Once we make a post request of a page that is not valid, it means we reached to last page, we set this.morePagesAvailable = false because there aren't more pages available.

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.

Ion2FullApp Ionic Wordpress
Ion2FullApp Ionic Wordpress
Ion2FullApp Ionic Wordpress

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

So 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

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.

Get wordpress posts by Category

On this fantastic 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.

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 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 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 Authentication Service 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

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.


The function to create a new comment is on post.ts file. There we first check if there is a logged user saved on the Native Storage. If there is a logged user on our Ionic app then we allow him to create a new comment, otherwise we show him an alert asking him to log in.

createComment(){
  let user: any;

  this.authenticationService.getUser()
  .then(res => {
    user = res;

    let alert = this.alertCtrl.create({
    title: 'Add a comment',
    inputs: [
      {
        name: 'comment',
        placeholder: 'Comment'
      }
    ],
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'Accept',
        handler: data => {
          let loading = this.loadingCtrl.create();
          loading.present();
          this.wordpressService.createComment(this.post.id, user, data.comment)
          .subscribe(
            (data) => {
              console.log("ok", data);
              this.getComments();
              loading.dismiss();
            },
            (err) => {
              console.log("err", err);
              loading.dismiss();
            }
          );
        }
      }
    ]
  });
  alert.present();
  },
  err => {
    let alert = this.alertCtrl.create({
      title: 'Please login',
      message: 'You need to login in order to comment',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Login',
          handler: () => {
            this.navCtrl.push(LoginPage);
          }
        }
      ]
    });
  alert.present();
  });
}

Authentication Register New User

Although we did not implement this functionality on the tutorial demo we are going to explain how to do it.


First of all it is essential to be authenticated and authorized to create new users, it means that you need to make a logged in request and this user should have permissions to create new users, for example it needs to be an Administrator.


The implementation will be similar as the login, with different username and password.

onSubmit(values){
  var username: Admin_Username;
  var password: Admin_Password;
  //only authenticated administrators can create users
  this.authenticationService.doLogin(username, password)
  .subscribe(
    res => {
      let user_data = {
        username: values.username,
        name: values.displayName,
        email: values.email,
        password: values.password
      };
      this.authenticationService.doRegister(user_data, res.json().token)
      .subscribe(
        result => {
          console.log(result);
        },
        error => {
          console.log(error);
        }
      );
    },
    err => {
      console.log(err);
    }
  )
}

Note the token is passed as a parameter on the url as same as in the comments section.

Next Steps

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

Now that you’ve learned more about how to communicate your ionic app with the wordpress REST API, you can focus on:

As you know we also sell complete ionic mobile 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 these Ionic templates and apply this new knowledge?