This package has been deprecated

Author message:

This package is deprecated, install 'ngx-wordpress' instead!

ng2-wp-api
TypeScript icon, indicating that this package has built-in type declarations

3.0.1 • Public • Published

npm Build Status npm

Angular WordPress Module

This library is designed to make it easy for your Angular application to request specific resources from a WordPress install.

Table of Contents

## Requirments

Wordpress setup.

## Installation

Install it with npm

npm install ng2-wp-api --save

## Usage

Import ShareButtonsModule in root module

import { WordPressModule } from 'ng2-wp-api';
 
@NgModule({
imports: [
    WordPressModule.forRoot('https://example.com')
  ]
})
 

Also add it in the child module that uses it (without forRoot)

@NgModule({
  imports: [
      WordPressModule
  ]
})
export class BlogModule { }
 
## Using the directives **For collection:**
<div class="feed" [wpCollection]="postsEndpoint" [wpArgs]="postsArgs" (wpResponse)="posts = $event.data">
    <ul>
      <li *ngFor="let post of posts">{{post.title.rendered}}</li>
    </ul>
</div>

See Directive Collection usage in depth.

  • Get a single post by Slug
<div class="single-post" [wpCollection]="endpoint" [wpArgs]="{slug: 'hello-world'}" (wpResponse)="single = $event.data[0]">
  <h1 [innerHtml]="single?.title?.rendered"></h1>
</div>
**For model:**
  • Get a single post by ID
<div class="single-post" [wpModel]="endpoint" [wpId]="29043" (wpResponse)="single = $event.data">
  <h1 [innerHtml]="single?.title?.rendered"></h1>
</div>

## Using the service **For collection:**

A basic example of getting 6 embedded posts:

/** Posts Response */
posts;
/** Posts Endpoint */
endpoint = WpEndpoint.posts;
/** Posts Args */
args = new {
    per_page: 6,
    _embed: true
};
 
this.wpService.collection()
  .endpoint(endpoint)       //or posts()
  .get(args)
  .subscribe((res: CollectionResponse) => {
    if(res.error){
      console.log(res.error);
    }
    else{
      this.posts = res.data;
      this.pagination = res.pagination;
    }
  });

See WpService Collection usage

**For model:**
/** Post Response */
post;
/** Post Endpoint */
endpoint = WpEndpoint.posts;
 
this.wpService.model()
  .endpoint(endpoint)     //or posts() or pages() or users() ..etc
  .get(id)
  .subscribe((res: ModelResponse) => {
    if(res.error){
      console.log(res.error);
    }
    else{
      this.post = res.data;
    }
  });

See WpService Model usage


## Add/Update/Delete
//add new post
wpService.model().posts().add(body);
 
//update page by id
wpService.model().pages().update(pageId, body);
 
//delete user by id
wpService.model().users().delete(userId);

## Authentication
 this.wpService.auth().basic('username', 'password').subscribe(
  (loggedInUser: WpUser)=> {
    console.log(loggedInUser);
  });
  • Cookies Authentication:
 this.wpService.auth().cookies().subscribe(
  (loggedInUser: WpUser)=> {
    console.log(loggedInUser);
  });

WpService Summary

Default Endpoints are : posts, pages, users, categories, tags, taxonomies, statuses, comments, media

    WpService
    ├── config 
    |    ├── baseUrl                       ** WordPress baseURL 
    |    ├── debug                         ** If enabled, Logs requested URL to the console
    |
    ├── collection()
    |    ├── endpoint(ep)
    |        ├── get(args?)                ** Get Collection of endpoint type.
    |        ├── more()                    ** Get Next page collection combined with any previous ones.
    |        ├── next()                    ** Get Next page collection.
    |        ├── prev()                    ** Get Prev page collection.
    |
    ├── model()
    |    ├── endpoint(ep)
    |        ├── get(id, args?)            ** Get Model by Id.
    |        ├── add(body)                 ** Add Model to WP.
    |        ├── update(id, body)          ** Update Model by Id.
    |        ├── delete(id)                ** Delete Model by Id.
    |
    ├── auth()
    |    ├── basic(username, password)     ** Basic authentication, returns loggedInUser.
    |    ├── cookies()                     ** Cookies authentication, returns loggedInUser.
    |    ├── logout()                      ** Removes authentication info from all requests.
    |    |
    |    ├── photon()                      ** Get post(s) images using photon service. 
    |        ├── getImage(post, propName)
    |        ├── getByQuery(post, domain, photonArgs)
## Embedded Responses

Usually when displaying a post, you want to display post's featured image, categories, tags, author and comments. The normal post response contains only the Id references which you will have to request each one of them individually.

Embedded responses are very useful to reduce the amount of http requets. you will get all the information you need in one response.

Embedding is triggered by setting the _embed=true in args, check Linking and Embedding

And now WpPost class will be useful to access the following properties:

post                        **  the original object
get(properyName)            **  get any property by its name
id()                        **  post id     
slug()                      **  post slug             
title()                     **  post title
content()                   **  post content
excerpt()                   **  post excerpt without the (read more) link
date()                      **  post date
link()                      **  post link
type()                      **  post type 
categories()                **  post categories array  
tags()                      **  post tags array
format()                    **  post format
author()                    **  post author object (WpUser)
featuredMedia()             **  check if post has featured image
featuredImageUrl(size)      **  get featured image by size, ("full", large", "medium") or 
                                any other available size in WP
##[Photon](https://developer.wordpress.com/docs/photon/)

To configure photon options, initialize them in the root module.

export function photonOptions() {
  return [
    { 'key': 'large', 'value': { w: 800, h: 360 } },
    { 'key': 'cropped', 'value': { crop: "160px,25,1400px,60" } }و
    { 'key': 'resized', 'value': { resize: "400,220" } }
  ]
}
 
imports[
    WordPressModule.forRoot('https://example.com', photonOptions())
  ]
})

Check Photon API for the parameters.

Then inject WpService in the component you want to call photon from:

constructor(private wpWpService){ 
}

In the template call photon for the post object with the option defined in the module wp.photon().getImage(post, option)

<img [src]="wp.photon().getImage(post, 'large')" />
<img [src]="wp.photon().getImage(post, 'cropped')" />
<img [src]="wp.photon().getImage(post, 'resized')" />

You can also query photon directly using the function wp.photon().getByQuery(post, photonArgs)

<img [src]="wp.photon().getByArgs(post, { w: 800, h: 400})" /> 
## Hints
  • For debug mode use:
imports[
    WordPressModule.forRoot('https://example.com', null, true)
    /** if you are using photon use this */
    // WordPressModule.forRoot('https://example.com', photonArgs(), true) 
]
## Issues

If you identify any errors in the library, or have an idea for an improvement, please open an issue. I am excited to see what the community thinks of this project, and I would love your input!

## Author

Murhaf Sousli

## License

npm

Dependencies (0)

    Dev Dependencies (0)

      Package Sidebar

      Install

      npm i ng2-wp-api

      Weekly Downloads

      2

      Version

      3.0.1

      License

      MIT

      Last publish

      Collaborators

      • murhaf