BLOG

wpapiでREST-APIが扱いやすくなるようです

| JavaScript

最近、NEXT.JSを使って構築しているんですが、
仕事的にはWordPressでの構築依頼が多いので、APIを使ってデータを取得することが多くなります。
簡単にWordPressのAPIを扱うにはREST-APIというのを使って取得するのが一番手っ取り早い

あとは、WordPressのプラグイン「WPGraphQL」を使って取得する方法があるようですね。
ぶっちゃけWPGraphQLを使うほうが色々と楽にデータ取得ができるみたいですが、
NEXT.JSを使ってるのにあんまりWordPressのプラグインに頼りたくないなと思ったのでこれは最終手段

オリジナルでAPIを作成する方法もあるけど、ぶっちゃけそこまでしなくてもいいかなと思っているので
REST-APIを使うという方法がいいかなと思ってます。

んで、wpapiっていうのがREST-APIが便利に使えるようになるってこと。

npm i -D wpapi

ひとまず、wpapiをインストールをして使うよっていうことです。

const WPAPI = require( 'wpapi' );
const wp = new WPAPI({endpoint: "https://example.com/wp-json"});

wp.posts().then((posts) => console.log(posts));

wpapiをインポートして、WordPressのAPIエンドポイントを設定します
そしたらwpでポストなりなんなりひっぱってこれます。
以下引用です。

  • wp.posts()…: Request items from the /posts endpoints
  • wp.pages()…: Start a request for the /pages endpoints
  • wp.types()…: Get Post Type collections and objects from the /types endpoints
  • wp.comments()…: Start a request for the /comments endpoints
  • wp.taxonomies()…: Generate a request against the /taxonomies endpoints
  • wp.tags()…: Get or create tags with the /tags endpoint
  • wp.categories()…: Get or create categories with the /categories endpoint
  • wp.statuses()…: Get resources within the /statuses endpoints
  • wp.users()…: Get resources within the /users endpoints
  • wp.media()…: Get Media collections and objects from the /media endpoints
  • wp.settings()…: Read or update site settings from the /settings endpoint (always requires authentication)

ここでよく使うのはposts types taxonomies categoriesあたりでしょうか。
あとはカスタム投稿でしょうか

wp.myPostType = wp.registerRoute( 'wp/v2', '/my-post-type/(?P<id>\\d+)' );
wp.myPostType().then((posts) => console.log(posts));

アイキャッチ画像を使う場合は.embed()を間にいれとけば画像もひっぱってこれる。

wp.posts().embed().then((posts) => console.log(posts));

これでざっくりとWordPressのデータをひっぱってこれるので問題ない。
カスタムフィールドを使う場合はAdvanced Custom Fieldsを使うと
RESTで使用する設定をしておけばひっぱってこれるので簡単かなと思います。

PAGE TOP