Ionic Angular Blog Site with WordPress REST API

Learn how to create a stunning Ionic Angular blog site using WordPress REST API. Follow this tutorial to set up your blog site.

How to Integrate WordPress in Ionic

  • Step 1: Create Ionic WordPress Project
  • Step 2: Generate Ionic Pages
  • Step 3: Import HttpClientModule in AppModule
  • Step 4: Set Up Routes
  • Step 5: Build WordPress Service in Ionic
  • Step 6: Display WordPress Posts Collection
  • Step 7: Show Post Details
  • Step 8: Run Development Server

Create Ionic WordPress Project

Let us full fill the first requirement that is to install the latest version of Ionic CLI.

npm install -g @ionic/cli

Use command to install the ionic, angular app:

ionic start ionic-wordpress-rest-api blank --type=angular

Get into the app directory:

cd ionic-wordpress-rest-api

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

 

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Generate Ionic Pages

Next, you have to generate pages for showing post collection and post details:

ionic g page posts
ionic g page post-detail

Import HttpClientModule in AppModule

In this step, you need add or import HttpClientModule in main app.modulet.ts file.

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [...],
  entryComponents: [...],
  imports: [
    HttpClientModule
  ],
  providers: [...],
  bootstrap: [...],
})
export class AppModule {}

Set Up Routes

To access post collection or post details pages, you need to update the routes inside the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
  {
    path: '',
    redirectTo: 'posts',
    pathMatch: 'full'
  },
  {
    path: 'posts',
    loadChildren: () => import('./posts/posts.module').then( m => m.PostsPageModule)
  },
  {
    path: 'post-detail/:id',
    loadChildren: () => import('./post-detail/post-detail.module').then( m => m.PostDetailPageModule)
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Build WordPress Service in Ionic

We have to create the angular service file, and it helps to handle the HTTP requests to fetch the data through the WordPress REST API.

ionic generate service shared/wpIonic

Subsequently, make sure to set up a WordPress website locally. You can use your WordPress site’s REST API to fetch the posts.

Generically, if anyhow you have a WP version less than 4.7, then you may take the help of the WP-API plugin.

Open the shared/wp-ionic.service.ts file and update the following code.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class WpIonicService {
  endpoint = `https://www.wordpress-site-name.com/wp-json/wp/v2/`;
  allPosts = null;
  pages: any;
 
  constructor( private httpClient: HttpClient ) { }
 
  getAllPosts(page = 1): Observable<any[]> {
    let options = {
      observe: "response" as 'body',
      params: {
        per_page: '6',
        page: ''+page
      }
    };
 
    return this.httpClient.get<any[]>(`${this.endpoint}posts?_embed`, options)
    .pipe(
      map((res: any) => {
        this.pages = res['headers'].get('x-wp-totalpages');
        this.allPosts = res['headers'].get('x-wp-total');
        return res['body'];
      })
    )
  }
 
  postDetails(id: any) {
    return this.httpClient.get(`${this.endpoint}posts/${id}?_embed`)
    .pipe(
      map((post) => {
        return post;
      })
    )
  }
}

Pass your WordPress site’s REST API url in the endpoint, use RxJS observables to get all the posts, including the post details page, via reactive programming.

Display WordPress Posts Collection

We need to import WpIonicService and LoadingController services, likewise add inside the constructor method.

Then call the getAllPosts() and infiniteLoad() methods to display posts list from WordPress website. The infiniteLoad() functions will be attached to the button and load the content when it reaches the last scroll position in the ionic app view.

Open and add code in posts.page.ts file:

import { Component, OnInit } from '@angular/core';
import { WpIonicService } from '../shared/wp-ionic.service';
import { LoadingController } from '@ionic/angular';
 
@Component({
  selector: 'app-posts',
  templateUrl: './posts.page.html',
  styleUrls: ['./posts.page.scss'],
})
export class PostsPage implements OnInit {
 
  Posts: any = [];
  postCount = null;
  page = 1;
 
  constructor(
    private wpService: WpIonicService, 
    private loadingController: LoadingController
  ) { }
 
  ngOnInit() {
    this.initPosts();
  }
 
  async initPosts() {
    let loading = await this.loadingController.create({
      message: 'Loading ...'
    });
 
    await loading.present();
 
    this.wpService.getAllPosts().subscribe((data) => {
      this.postCount = this.wpService.allPosts;
      this.Posts = data;
      loading.dismiss();
    });
  }
 
  infiniteLoad(e: any) {
    this.page++;
 
    this.wpService.getAllPosts(this.page).subscribe((data) => {
      this.Posts = [...this.Posts, ...data];
      e.target.complete();
 
      // Disable loading when reached last
      if (this.page == this.wpService.pages) {
        e.target.disabled = true;
      }
    });
  }
 
}

The ion-card is the better option to show the post list in a card view, use ngFor directive to loop over the post collection, then render the content with the help of innerHTML property.

Likewise, define the ion-infinite-scroll property and add the ionInfinite event that will trigger the infiniteLoad() method to get the post when it reached the bottom of the page.

Open and place code in posts.page.html file:

<ion-header>
  <ion-toolbar color="success">
    <ion-title>positronX Blog</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content padding>
  <ion-item>
    <ion-label>
      <strong>Total Posts</strong>
    </ion-label>
    <ion-badge color="danger" *ngIf="postCount">{{ postCount }}</ion-badge>
  </ion-item>
  <ion-card *ngFor="let post of Posts">
    <ion-card-header>
      <ion-card-title [innerHTML]="post.title.rendered"></ion-card-title>
      <ion-card-subtitle>{{ post.date_gmt | date }}</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      <div [innerHTML]="post.excerpt.rendered"></div>
      <ion-button expand="full" fill="clear" [routerLink]="['/', 'post-detail', post.id]">Read More</ion-button>
    </ion-card-content>
  </ion-card>
  <ion-infinite-scroll threshold="120px" (ionInfinite)="infiniteLoad($event)">
    <ion-infinite-scroll-content loadingText="Fetching Posts">
    </ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

Show Post Details

In this step, we have to extract the post id; we can get the post id using the ActivatedRoute service, pass that id into the postDetails() method and implement the single detail page in the ionic wordpress app.

Add code in post-detail.page.ts file:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { WpIonicService } from '../shared/wp-ionic.service';
@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.page.html',
  styleUrls: ['./post-detail.page.scss'],
})
export class PostDetailPage implements OnInit {
  postDetial: any;
  constructor(
    private activatedRoute: ActivatedRoute,
    private wpService: WpIonicService
  ) {}
  ngOnInit() {
    let id = this.activatedRoute.snapshot.paramMap.get('id');
    this.wpService.postDetails(id).subscribe((data) => {
      this.postDetial = data;
    });
  }
  goToOrgPost() {
    window.open(this.postDetial.link, '_blank');
  }
}

 

In this last step, you have to open the post-detail.page.html file and carefully place the recommended code within the file:

<ion-header>
  <ion-toolbar color="danger">
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/posts"></ion-back-button>
    </ion-buttons>
    <ion-title>{{ postDetial?.title.rendered }}</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content padding>
  <div *ngIf="postDetial">
    <div [innerHTML]="postDetial.content.rendered" padding></div>
  </div>
</ion-content>
<ion-footer color="secondary">
  <ion-toolbar>
    <ion-button expand="full" fill="clear" (click)="goToOrgPost()">
      Check Original Post
    </ion-button>
  </ion-toolbar>
</ion-footer>

Run Development Server

To start the app, you may install the ionic lab package through node package manager:

npm i @ionic/lab --save-dev

Now, you can execute following command to serve the ionic app:

ionic serve -l
Ionic 7 WordPress client

#ionic #angular  #wordpress 

Ionic Angular Blog Site with WordPress REST API
1.60 GEEK