アプリケーションパスワードの設定をして権限が有る前提です。
これにより、APIで投稿の作成、更新、削除が可能になります。
今回は更新と削除もやってみましょう。
更新
リファレンス
公式を見ると以下のように書かれています。
ほとんど作成と一緒で違うのはエンドポイント。更新したい投稿のidを入れるとこでしょう。
POST /wp/v2/posts/<id>
| 引数 | 説明 |
|---|---|
| id | Unique identifier for the object. |
| date | The date the object was published, in the site's timezone. |
| date_gmt | The date the object was published, as GMT. |
| slug | An alphanumeric identifier for the object unique to its type. |
| status | A named status for the object. 次のいずれか: publish, future, draft, pending, private |
| password | A password to protect access to the content and excerpt. |
| title | The title for the object. |
| content | The content for the object. |
| author | The ID for the author of the object. |
| excerpt | The excerpt for the object. |
| featured_media | The ID of the featured media for the object. |
| comment_status | Whether or not comments are open on the object. 次のいずれか: open, closed |
| ping_status | Whether or not the object can be pinged. 次のいずれか: open, closed |
| format | The format for the object. 次のいずれか: standard, aside, chat, gallery, link, image, quote, status, video, audio |
| meta | Meta fields. |
| sticky | Whether or not the object should be treated as sticky. |
| template | The theme file to use to display the object. |
| categories | The terms assigned to the object in the category taxonomy. |
| tags | The terms assigned to the object in the post_tag taxonomy. |
APIを叩く
アプリケーションパスワードで認証をヘッダーに付与することを忘れずに。
エンドポイントはhttp://localhost:8000/wp-json/wp/v2/posts/8 (idは適宜変更)
リクエストボディのJSONは
{
"title": "Update Title",
"status": "publish"
}
これで投稿が更新されタイトルが変更され、statusがpublishとなり「下書き」状態が、「公開済み」になります。
ちなみにPOSTメソッドとなっていますが、PUTやPATCHメソッドでも更新が反映されました。
削除
リファレンス
DELETE /wp/v2/posts/<id>
| 引数 | 説明 |
|---|---|
| id | Unique identifier for the object. |
| force | Whether to bypass trash and force deletion. |
APIを叩く
こちらもアプリケーションパスワードで認証をヘッダーに付与することを忘れずに。
エンドポイントはhttp://localhost:8000/wp-json/wp/v2/posts/8 (idは適宜変更)
リクエストボディはなくてもOK。DELETEメソッドなのを忘れずに!
これでstatusがtrashとなりゴミ箱に移動することが確認できます。
もう一度同じAPIを叩くと410のステータスでエラーが返ってきます。
{
"code": "rest_already_trashed",
"message": "その投稿はすでに削除されています。",
"data": {
"status": 410
}
}
以下をリクエストボディに入れてAPIを叩くとゴミ箱にも残らず完全消去となります。
{
"force": true
}
完全消去した後に同じAPIを叩くと404のエラーでレスポンスが返ってきます。
WordPress REST APIはエラー作り込んでますね!好感持てます!
{
"code": "rest_post_invalid_id",
"message": "無効な投稿 ID です。",
"data": {
"status": 404
}
}
まとめ
WordPress REST APIで投稿の更新、削除をしてみました。
わりと簡単で、一回やれば覚えられそうですね!