🌐 REST API とは

REST API(Representational State Transfer API)とは、URLを叩くだけでデータをやり取りできる仕組みです。WordPressは標準でREST APIを持っており、投稿・カテゴリー・ユーザーなどのデータをJSON形式で取得・操作できます。

標準APIの例

  • GET /wp/v2/posts — 投稿一覧を取得
  • GET /wp/v2/posts/1 — ID:1の投稿を取得
  • POST /wp/v2/posts — 投稿を作成
  • DELETE /wp/v2/posts/1 — 投稿を削除

カスタムAPIで実現できること

  • モバイルアプリとのデータ連携
  • React/Vueなどとの組み合わせ
  • 外部サービスへのデータ提供
  • 独自の検索・フィルター機能

💡 APIのURLを確認する

ブラウザで https://あなたのサイト/wp-json/wp/v2/posts にアクセスすると、投稿データがJSON形式で表示されます。WordPressのREST APIが有効になっているか確認できます。

⚙️ カスタムエンドポイントの作成

register_rest_route() を使って独自のエンドポイントを追加します。

add_action( 'rest_api_init', 'mfp_register_routes' ); function mfp_register_routes() { // GETリクエスト: 人気投稿を取得するエンドポイント register_rest_route( 'mfp/v1', // 名前空間(プラグイン名/バージョン) '/popular-posts', // エンドポイントのパス array( 'methods' => 'GET', 'callback' => 'mfp_get_popular_posts', 'permission_callback' => '__return_true', // 誰でもアクセス可 'args' => array( 'count' => array( 'default' => 5, 'sanitize_callback' => 'absint', ), ), ) ); // POSTリクエスト: ログインユーザーのみデータを送信できるエンドポイント register_rest_route( 'mfp/v1', '/save-note', array( 'methods' => 'POST', 'callback' => 'mfp_save_note', 'permission_callback' => 'is_user_logged_in', // ログイン必須 ) ); } // コールバック関数: 人気投稿を返す function mfp_get_popular_posts( $request ) { $count = $request->get_param( 'count' ); $posts = get_posts( array( 'numberposts' => $count, 'orderby' => 'comment_count', 'order' => 'DESC', ) ); $data = array(); foreach ( $posts as $post ) { $data[] = array( 'id' => $post->ID, 'title' => get_the_title( $post ), 'url' => get_permalink( $post ), ); } return new WP_REST_Response( $data, 200 ); }

このエンドポイントには https://あなたのサイト/wp-json/mfp/v1/popular-posts?count=3 でアクセスできます。

🔒 認証とセキュリティ

permission_callback の設定

// パターン1: 誰でもアクセス可(公開データ) 'permission_callback' => '__return_true' // パターン2: ログインユーザーのみ 'permission_callback' => 'is_user_logged_in' // パターン3: 管理者のみ 'permission_callback' => function() { return current_user_can( 'manage_options' ); } // パターン4: nonceによる検証(JavaScriptからの呼び出しに推奨) 'permission_callback' => function( $request ) { $nonce = $request->get_header( 'X-WP-Nonce' ); return wp_verify_nonce( $nonce, 'wp_rest' ); }

エラーレスポンスの返し方

function mfp_save_note( $request ) { $note = $request->get_param( 'note' ); if ( empty( $note ) ) { // エラーレスポンスを返す return new WP_Error( 'missing_note', // エラーコード 'note パラメータが必要です', // メッセージ array( 'status' => 400 ) // HTTPステータスコード ); } $note = sanitize_textarea_field( $note ); update_user_meta( get_current_user_id(), 'mfp_note', $note ); return new WP_REST_Response( array( 'message' => '保存しました' ), 200 ); }

⚠️ permission_callback を省略しない

WordPress 5.5以降、permission_callback を省略すると管理画面に警告が表示されます。必ず設定してください。

💻 JavaScriptからAPIを呼び出す

// wp_localize_script でフロントエンドに nonce を渡す(PHP側) wp_localize_script( 'mfp-script', 'mfpApi', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ), ) ); // JavaScript側でAPIを呼び出す fetch( mfpApi.root + 'mfp/v1/popular-posts?count=5' ) .then( res => res.json() ) .then( data => { data.forEach( post => { console.log( post.title, post.url ); }); }); // 認証が必要なPOSTリクエスト fetch( mfpApi.root + 'mfp/v1/save-note', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': mfpApi.nonce }, body: JSON.stringify({ note: 'メモの内容' }) }) .then( res => res.json() ) .then( data => console.log( data.message ) );

✏️ 演習:自分のAPIエンドポイントを作ろう

📝 課題

  1. GET /mfp/v1/search?keyword=XXX でカスタム投稿タイプを検索できるエンドポイントを作成
  2. 結果をID・タイトル・URLのJSON配列で返す
  3. JavaScript の fetch() でエンドポイントを呼び出し、検索結果を画面に表示する

✅ この章のチェックリスト

  • register_rest_route() でエンドポイントを作成できた
  • permission_callback で認証を実装できた
  • WP_REST_Response と WP_Error を使い分けられた
  • JavaScriptからAPIを呼び出せた

🔗 関連ページ・次のステップ

📘 前提知識

🚀 あわせて学ぶ

📚 補足