Show a single WordPress article post in an Ionic Angular app.

Posted on Updated on

It took me a little while to do this nicely, but I’m happy with this version:    This will help you get a specific WP post with a wp_id.

This is not a full example, but close enough. If you know what you are doing, this should be easy for you.

 

 

I’m calling this code from another page which will link to the WP article.

<a style="width:100%"style="text-decoration:none;"class="item"href="#"(click)="OpenSinglePost(6872, 'Custom Article title ')">Show the Article</a>
The code behind on the .ts file:
OpenSinglePost(postid, pagetitle: string)
{
  this.navCtrl.push(WpArticleItemPage, {postId: postid, pagetitle: pagetitle });
}

Showing the actual WP article page:

 

 

wp-article-item.ts

 

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, Loading } from 'ionic-angular';
import { ProgressHttp } from "angular-progress-http";

@IonicPage()
@Component({
selector: 'page-wp-article-item',
templateUrl: 'wp-article-item.html',
})

export class WpArticleItemPage
{
postId: number;
loader: Loading;
post_title: string;
post_content: string;
url: string;

constructor(
public navCtrl: NavController,
public navParams: NavParams,
public loadingCtrl: LoadingController,
private http: ProgressHttp)
{

this.presentLoading();
this.postId = navParams.get('postId');
this.post_title = navParams.get('pagetitle');
console.log("this.postId: " + this.postId);
this.url ='https://www.c4israel.com.au/wp-json/wp/v2/pages/'+this.postId;
this.http
.get( this.url ) // The URL
.map( res => res.json()) // putting an async makes it get stuck forever.
.subscribe( data =>
{

//this.post_title = data.title.rendered;
this.post_content =this.striplinks(data.content.rendered);
console.log(data);
this.loader.dismiss()
})
};

// This currently solves the URL problem

striplinks(text)
{
var re = /<a\s.*?href=[\"\'](.*?)[\"\']*?>(.*?)<\/a>/g;
var str = text;
var subst ='$2';
var result = str.replace(re, subst);
return result;
}

presentLoading() {
this.loader =this.loadingCtrl.create({
content: "Retrieving data..."
});

this.loader.present();
}
}

Yes, WP doesn’t format code nicely – I know.

Now for the front-end and display the WP article.

 

wp-article-item.html

<ion-header>
<ion-navbar color="primary">
<ion-title>{{ post_title }}</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>
< d i v [innerHTML]="post_content"></ d i v >
</ion-content>

(Just fix the div tags up. It's a WordPress thing)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s