WordPressではREST APIが用意されています。
今回はカスタム投稿とカスタムタクソノミーで使用できるようにします。
デフォルトではfalseになっている以下を追加するだけです。
'show_in_rest' => true,
add_action('init', function() {
$post_type = 'custom_post';
$post_name = 'カスタム投稿';
register_post_type(
$post_type,
array(
'label' => $post_name,
'description' => '',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'hierarchical' => false,
'rewrite' => array('slug' => $post_type, 'with_front' => true),
'query_var' => true,
'has_archive' => true,
'menu_position' => 20,
'show_in_rest' => true,
'supports' => array('title','thumbnail'),
'taxonomies' => array('case_type'),
'labels' => array(
'name' => $post_name,
'singular_name' => $post_name,
'menu_name' => $post_name,
'add_new' => '新規追加',
'add_new_item' => '新規'.$post_name.'追加',
'edit' => '編集',
'edit_item' => $post_name. 'を編集',
'new_item' => '新規'.$post_name,
'view' => '表示',
'view_item' => $post_name.'を表示',
'search_items' => $post_name.'を検索',
'not_found' => '見つかりません。',
'not_found_in_trash' => 'ゴミ箱にはありません。',
'parent' => '親記事',
),
'map_meta_cap' => true
));
});
カスタムタクソノミーの場合は以下になります。
register_taxonomy(
'custom_taxonomy', null,
array(
'hierarchical' => true,
'label' => 'カスタムタクソノミー',
'show_ui' => true,
'rewrite' => true,
'query_var' => false,
'show_admin_column' => true,
'singular_label' => 'カスタムタクソノミー',
'show_in_rest' => true,
'labels' => [
'edit_item' => '項目を編集',
'add_new_item' => '新規項目を追加',
'not_found' => '項目がありません。',
],
)
);
これだけでAPIにアクセスするとデータが返ってきます。
例:https:/hogehoge.com/wp-json/wp/v2/custom_post
ブラウザから確認する場合は以下の拡張機能がおすすめです。
ちなみにアクセスされたくないAPIもあります。
以下でユーザー名が表示されてしまいます。
https:/hogehoge.com/wp-json/wp/v2/users
パスワードは表示されませんが企業などの場合は氏名を使用して管理している場合がありますので注意が必要です。
以下のコードをfunctions.phpに追加することで非表示にすることができます。
function my_filter_rest_endpoints( $endpoints ) {
if ( isset( $endpoints['/wp/v2/users'] ) ) {
unset( $endpoints['/wp/v2/users'] );
}
if ( isset( $endpoints['/wp/v2/users/(?P[\d]+)'] ) ) {
unset( $endpoints['/wp/v2/users/(?P[\d]+)'] );
}
return $endpoints;
}
add_filter( 'rest_endpoints', 'my_filter_rest_endpoints', 10, 1 );
カスタム投稿はデフォルトでは非表示なのにユーザー情報もデフォルトで非表示でもいいのにな…