register_rest_field()


WordPress関数register_rest_field()は、REST APIにカスタムフィールドを登録するために使用されます。この関数は、投稿タイプやタクソノミーのデータを拡張する場合に便利です。

構文

register_rest_field( string $object_type, string $attribute, array $args );

引数の説明:

  • $object_type (string) — フィールドを追加する投稿タイプやタクソノミー。
  • $attribute (string) — 登録するフィールドの名前。
  • $args (array) — フィールドの動作を定義するための引数の配列。

例1: カスタムフィールドを登録する

特定の投稿タイプにカスタムフィールドを追加します。

register_rest_field( 'post', 'custom_field', array(
    'get_callback' => function( $post ) {
        return get_post_meta( $post['id'], 'custom_field', true );
    },
    'schema' => array(
        'type' => 'string',
        'description' => 'カスタムフィールドの説明',
    ),
));

例2: タクソノミーにフィールドを追加

タクソノミー「category」にフィールドを追加します。

register_rest_field( 'category', 'extra_data', array(
    'get_callback' => function( $term ) {
        return get_term_meta( $term['id'], 'extra_data', true );
    },
    'schema' => array(
        'type' => 'string',
        'description' => 'カテゴリ用追加データ',
    ),
));

例3: 読み取り専用フィールドを追加

読み取り専用のフィールドを投稿タイプに追加します。

register_rest_field( 'post', 'read_only_field', array(
    'get_callback' => function( $post ) {
        return '読み取り専用の値';
    },
    'schema' => array(
        'type' => 'string',
        'readonly' => true,
        'description' => 'このフィールドは編集できません',
    ),
));

例4: 数値型フィールドを登録

数値型のカスタムフィールドを登録します。

register_rest_field( 'post', 'numeric_field', array(
    'get_callback' => function( $post ) {
        return (int) get_post_meta( $post['id'], 'numeric_field', true );
    },
    'schema' => array(
        'type' => 'integer',
        'description' => '数値データ',
    ),
));

例5: 条件付きでフィールドを追加

特定の条件を満たす場合のみフィールドを返します。

register_rest_field( 'post', 'conditional_field', array(
    'get_callback' => function( $post ) {
        if ( get_post_meta( $post['id'], 'condition_met', true ) ) {
            return '条件が満たされました';
        }
        return null;
    },
    'schema' => array(
        'type' => 'string',
        'description' => '条件付きフィールド',
    ),
));

関連機能: