1
1

結論

rest_api_ini フィルタを使おう。
ついでに勝手に使われるといけないので以下のフィルタを使って、認証処理も実装しましょう。

  • determine_current_user
  • rest_authentication_errors

作成するエンドポイント

https://ブログドメイン/wp-json/myapi/v1/helloWorld

コード

完成系
// 使いたいAPIの中身を書こう
function helloWorld()
{
  echo 'Hello World!';
}

// 自作のAPIを作る
add_action('rest_api_init', function () {
    register_rest_route('myapi/v1', '/hello', array(
        'methods' => 'GET',
        'callback' => 'helloWorld',
        'permission_callback' => function () {
            return current_user_can('read'); // 認証が必要
        },
    ));
});

// ユーザ認証を行う
add_filter('determine_current_user', function ($user_id) {
    // 認証情報を取得
    if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
        $username = sanitize_user($_SERVER['PHP_AUTH_USER']);
        $password = $_SERVER['PHP_AUTH_PW'];

        // ユーザーの認証を行う
        $user = wp_authenticate($username, $password);
        if (is_wp_error($user)) {
            return null;
        }

        return $user->ID;
    }

    return $user_id;
}, 20);

// ユーザ認証の成功判定
add_filter('rest_authentication_errors', function ($result) {
    if (!empty($result)) {
        return $result;
    }

    if (!is_user_logged_in()) {
        return new WP_Error('REST APIを使うための認証ができませんでした', 'You are not currently logged in.', array('status' => 401));
    }

    return $result;
});
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1