How to Consume WordPress Rest API in Ionic 5 Angular

In this Ionic 5 WordPress REST API tutorial, you will learn how to implement WordPress REST API in the Ionic 5 Angular app. We will give you a simple example of the Ionic 5 WordPress API from scratch.

We will create the Ionic Angular project using the most powerful HttpClient API and teach you how to consume the WordPress REST API in the Ionic application.

WordPress is a free and open-source CMS (content management system) formulated in PHP and aligned with a MySQL or MariaDB database. WordPress is a unique blogging platform. You can use it for building flawless and faster websites.

The intuitive ecosystem of wordpress is flexible and less complicated, and it provides a ton of features. You can create almost any type of functionality pretty quickly because of its most popular plugin feature.

The WordPress REST API is an interface that helps developers to access WordPress from the outside. In this guide, you will learn how to access the wordpress blog site and create an interactive ionic blog site using WordPress Rest API.

Ionic 5 Angular WordPress Rest API Example

  • Step 1: Install Ionic App
  • Step 2: Create Blog Pages
  • Step 3: Add Http Client Module
  • Step 4: Update Routes
  • Step 5: Implement WordPress API
  • Step 6: Show WordPress Data in Ionic
  • Step 7: View App in Browser

Install Ionic App

Welcome to the ionic wordpress API tutorial’s first step; we will take a look at how to install the ionic CLI for ionic development.

npm install -g @ionic/cli

Understand API implementation in ionic from a more theoretical point of view requires a new ionic app to be ready.

For that, use the command to create the ionic project.

ionic start ionic-wordpress-demo blank --type=angular

Create Blog Pages

In this step, we need to create pages for incorporating and displaying data fetched from wordpress API.

ionic g page blog

ionic g page single

Add Http Client Module

To make HTTP requests, you need to add HttpClientModule from ‘@angular/common/http’ package in app.modulet.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';


import { HttpClientModule } from '@angular/common/http';



@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})

export class AppModule {}

Update Routes

We will go through the app/app-routing.module.ts file; you have to update the Routes array, remote the home route, change redirectTo to the blog page, and add the id in the single page.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'blog',
    pathMatch: 'full'
  },
  {
    path: 'blog',
    loadChildren: () => import('./blog/blog.module').then( m => m.BlogPageModule)
  },
  {
    path: 'single/:id',
    loadChildren: () => import('./single/single.module').then( m => m.SinglePageModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Implement WordPress API in Ionic

Next, we will be looking at API integration in ionic. We look at ionic, angular service, which helps wordpress API be added in ionic, angular app.

Ideally, we will create a service file and add the wordpress API for fetching blog collection and a single blog page.

ionic generate service wordpress

Head over to app/wordpress.service.ts and insert the provided code in the file.

Make sure to grab your API from wordpress dashboard and define to the API_URL variable.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})

export class WordPressService {

  API_URL = `https://your_site.com/wp-json/wp/v2/`;
  allBlogs = null;
  pages: any;
 
  constructor( private http: HttpClient ) { }
 
  fetchData(page = 1): Observable<any[]> {
    let options = {
      observe: "response" as 'body',
      params: {
        per_page: '5',
        page: ''+page
      }
    };
 
    return this.http.get<any[]>(`${this.API_URL}posts?_embed`, options)
    .pipe(
      map((response) => {
        this.pages = response['headers'].get('x-wp-totalpages');
        this.allBlogs = response['headers'].get('x-wp-total');
        return response['body'];
      })
    )
  }
 
  single(id) {
    return this.http.get(`${this.API_URL}posts/${id}`)
    .pipe(
      map((data) => {
        return data;
      })
    )
  }

}

Show WordPress Data in Ionic

We will use the WordPress service that we built earlier to show you how to render the data from the wordpress blog site using API.

Update code in blog.page.ts file:

import { Component, OnInit } from '@angular/core';
import { WordPressService } from '../wordpress.service';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.page.html',
  styleUrls: ['./blog.page.scss'],
})

export class BlogPage implements OnInit {

  WpItems = [];
  blogCount = null;
  page = 1;
 
  constructor(
    private wordpress: WordPressService, 
    private loadingCtrl: LoadingController
  ) { }
 
  ngOnInit() {
    this.getWpData();
  }
 
  async getWpData() {
    let loading = await this.loadingCtrl.create({
      message: 'Data Loading ...'
    });
 
    await loading.present();
 
    this.wordpress.fetchData().subscribe((data) => {
      this.blogCount = this.wordpress.allBlogs;
      this.WpItems = data;
      loading.dismiss();
    });
  }
 
  loadData(e) {
    this.page++;
 
    this.wordpress.fetchData(this.page)
      .subscribe((data) => {
      this.WpItems = [...this.WpItems, ...data];
      e.target.complete();
      if (this.page == this.wordpress.pages) {
        e.target.disabled = true;
      }
    });
  }

}

After retrieving the data, we will bind it to an ionic HTML template, hence open blog.page.html and update the below code within the file.

<ion-header>
  <ion-toolbar>
    <ion-title>RemoteStack</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label>
      <strong>RS Blog</strong>
    </ion-label>
    <ion-badge color="danger" *ngIf="blogCount">{{ blogCount }}</ion-badge>
  </ion-item>

  <ion-card *ngFor="let item of WpItems">
    <ion-card-header>
      <ion-card-title [innerHTML]="item.title.rendered"></ion-card-title>
      <ion-card-subtitle>{{ loadData.date_gmt | date }}</ion-card-subtitle>
    </ion-card-header>

    <ion-card-content>
      <div [innerHTML]="item.excerpt.rendered"></div>
      <ion-button expand="full" fill="clear" [routerLink]="['/', 'single', item.id]">Load More</ion-button>
    </ion-card-content>
  </ion-card>

  <ion-infinite-scroll threshold="140px" (ionInfinite)="loadData($event)">
    <ion-infinite-scroll-content loadingText="Getting Blog Items">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>

</ion-content>

Lastly, we will be looking at how to get to the details page and redirect the user to the original page of the blog.

Update code in single.page.ts file:

import { Component, OnInit } from '@angular/core';
import { WordPressService } from '../wordpress.service';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-single',
  templateUrl: './single.page.html',
  styleUrls: ['./single.page.scss'],
})

export class SinglePage implements OnInit {

  postInfo: any;
 
  constructor(
    private actRoute: ActivatedRoute, 
    private wpService: WordPressService, 
  ) { }
 
  ngOnInit() {
    let id = this.actRoute.snapshot.paramMap.get('id');
    this.wpService.single(id)
    .subscribe((item) => {
      this.postInfo = item;
    });
  }
 
  visitRealPost() {
    window.open(this.postInfo.link, '_blank');
  }  

}

Update single.page.html file.

<ion-header>
  <ion-toolbar>
    <ion-buttons>
      <ion-back-button defaultHref="/blog"></ion-back-button>
    </ion-buttons>
    <ion-title>{{ postInfo?.title.rendered }}</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

  <div *ngIf="postInfo">
    <div [innerHTML]="postInfo.content.rendered" padding></div>
  </div>

</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-button expand="full" (click)="visitRealPost()">
      View Real Blog
    </ion-button>
  </ion-toolbar>
</ion-footer>

View App in Browser

Finally, we’ll get to the root of the matter, where we will be using the provided command to see wordpress API in action.

npm i @ionic/lab --save-dev
ionic serve -l

You may use the given url if developing app locally.

http://localhost:8200/

How to Consume WordPress Rest API in Ionic 5 Angular

Summary

In this tutorial, you have learned how to integrate WordPress rest API in the Ionic application, how to create an ionic wordpress blog site using wordpress API.