WP REST APIの基盤を使って、WordPressからJSON-LDを出力させる
WP REST APIのドキュメントを見ていたらできそうだったので覚書。 独自のエンドポイントを追加する WP REST APIは以下の様な書き方で独自のAPIエンドポイントを追加できます。 add_action( ‘r […]
目次
WP REST APIのドキュメントを見ていたらできそうだったので覚書。
独自のエンドポイントを追加する
WP REST APIは以下の様な書き方で独自のAPIエンドポイントを追加できます。
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
} );
/**
* Grab latest post title by an author!
*
* @param array $data Options for the function.
* @return string|null Post title for the latest,
* or null if none.
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
From:Adding Custom Endpoints | WP REST API v2 Documentation
WP_REST_Responseでヘッダーやステータスを変更する
「my_awesome_func」の方でレスポンスを用意するわけですが、「WP_REST_Response」というクラスを利用することでHTTPステータスやリクエストヘッダーを変更することができます。
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
$response = new WP_REST_Response( $posts[0]->post_title );
$response->set_status( 201 );
return $response;
}
配列をそのままreturnするのではなく、WP_REST_Responseクラスの中に入れてオブジェクトごとreturnさせます。
上のコードであれば、HTTPステータスが201で返ります。
JSON-LDを返す
で、$response->header();という処理を使えばレスポンスヘッダーを弄れるので、Content-typeをJSON-LDにしてJSON-LDを返すようにしましょう。
function my_awesome_func( WP_REST_Request $request ) {
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
$data = array(
'@context' => 'https://schema.org',
'@type' => 'LocalBusiness',
'name' => 'Example Store',
'description' => 'Example store description',
'telephone' => '000-000-0000'
);
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom header
$response->header( 'Content-type', 'application/ld+json' );
return $response;
}
実行結果

ちゃんとJSON-LDとして返ってきています。
あとはWP_REST_Responseに入れる値をWPから動的に取り出せるようにすれば、WordPressからJSON-LDを出力することができるかなと思います。
おまけ:GeoJSONなど
GeoJSONを返したくなった場合はこうすればOKです。
# GeoJSON $response->header( 'Content-type', 'application/vnd.geo+json' );
Content-typeさえわかれば何にでも変えれそうですが、データ自体はJSON形式で出力されるのでTurtleやXMLで返すのはもう一手間必要or無理っぽいです。