Help us understand the problem. What is going on with this article?

WordPress: REST API メモ v2

More than 3 years have passed since last update.

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 );
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした