2021/04/20
API /Wordpress /
WP REST API カスタマイズ方法

wpの各関数を使って取得していきます。カテゴリーも取得する方法も記入します。
また、カスタム投稿タイプを利用し任意のエンドポイントを構築。さらにそこに取得したいデータたちを格納していきます。
add_action('rest_api_init', 'add_custom_endpoint');
function add_custom_endpoint()
{
register_rest_route('custom/v1', '/name', array(
'methods' => 'GET',
'callback' => 'name_api',
));
}
function name_api(WP_REST_Request $request)
{
$args = array(
'post_type' => 'post name',
'post_status' => 'publish',
);
$the_query = get_posts($args);
foreach ($the_query as $post) {
$news_category = get_the_terms($post->ID, 'category name');
}
$the_query = new WP_Query($args);
$data = array();
while ($the_query->have_posts()) {
$the_query->the_post();
$data[] = array(
'id' => get_the_ID(),
'date' => get_the_date('Y/m/d', get_the_ID()),
'title' => get_the_title(),
'categories' => $news_category,
'tags' => get_the_tags(),
'thumbnail' => get_the_post_thumbnail_url(get_the_ID(), 'full'),
'content' => get_the_content(),
);
}
$response = new WP_REST_Response($data); // HTTPステータスやリクエストヘッダーを変更
$response->set_status(200);
return $response;
}
ANY-URL/wp-json/custom/v1/name/
上記の設定では↑のURLでエンドポイントが作成され取得することができます。