15
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPress: REST API メモ v2

Posted at

WordPressのREST APIを使用するときのメモです。
個人の環境によって変わってくる所もあると思うので、参考までにご覧ください。

下記のプラグインを使用する想定で書いています。

・プラグイン
カスタムフィールドの登録:Advanced Custom Field
カスタムポストの登録:Custom Post Type UI

投稿のエンドポイント

http://example.com/wp-json/wp/v2/posts/<ID>

個別ページのエンドポイント

http://example.com/wp-json/wp/v2/pages/<ID>

Advanced Custom Fieldsの内容をAPIに追加する時

functions.php
function wp_rest_api_alter() {
    $params = array(
        'get_callback'    => function($data, $field, $request, $type){
            if (function_exists('get_fields')) {
                return get_fields($data['id']);
            }
            return [];
            },
        'update_callback' => null,
        'schema'          => null,
    );
    register_api_field( 'page', 'fields', $params );
    register_api_field( 'post', 'fields', $params );
}
add_action( 'rest_api_init', 'wp_rest_api_alter');

カスタムポストタイプのエンドポイントを作る

http://example.com/wp-json/wp/v2/<custom-post-type>

functions.php
function sb_add_cpts_to_api() {
    global $wp_post_types;

    // Add CPT slugs here
    $arr = ['<post-typeA>','<post-typeB>','<post-typeC>'];

    foreach( $arr as $key ) {

    // If the post type doesn't exist, skip it
    if( !$wp_post_types[$key] )
        continue;

        $wp_post_types[$key]->show_in_rest = true;
        $wp_post_types[$key]->rest_base = $key;
    }
}
add_action( 'init', 'sb_add_cpts_to_api', 30 );
15
20
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
15
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?