2
1

More than 3 years have passed since last update.

【Wordpress】Smart Custom Fields(SCF)で繰り返しのカスタムフィールドをコード定義&REST API出力する

Last updated at Posted at 2020-09-16

やりたいこと

SCFの繰り返しのフィールドをコードで管理し、更にAPIで出力する

やりかた

コード定義

functions.php
function my_register_fields( $settings, $type, $id, $meta_type ) {
    // 特定のタイプにだけ、このカスタムフィールドを表示する場合下記をコメントアウト
    //if($type !== 'post'){
    //    return $settings;
    //} 

    // SCF::add_setting( 'ユニークなID', 'メタボックスのタイトル' );
    $Setting = SCF::add_setting( 'id-1', 'functions.php から追加 その1' );

    // $Setting->add_group( 'ユニークなID', 繰り返し可能か, カスタムフィールドの配列 );
    $Setting->add_group( 'group-name-1', true, array(
        array(
            'name'  => 'field-1',
            'label' => 'テストフィールド',
            'type'  => 'text',
        ),
        array(
            'name'    => 'field-2',
            'label'   => 'テストフィール2',
            'type'    => 'text',
            'default' => 2,
        ),
    ) );

    $settings[] = $Setting;
    return $settings;
}
add_filter( 'smart-cf-register-fields', 'my_register_fields', 10, 4 );

add_groupの際に第2引数にtrueを設定

API出力

add_groupの際に指定したユニークなIDを使う

functions.php

function rest_scf_add_field()
{
    register_rest_field(
        'post', // 追加する投稿タイプ(カスタム投稿なら、その投稿タイプを指定する),
        'scf', // 追加するフィールド名
        [
            'get_callback' => function(){
                return SCF::get('group-name-1'); // add_groupで指定したID
            },
            'update_callback' => null,
            'schema' => null,
        ],
    );

}

出力イメージ(2回繰り返している)

- scf
    - 0
        - field-1
            - ほげ
        - field-2
            - ほげ2
    - 1
        - field-1
            - ほげ
        - field-2
            - ほげ2

ちなみに、Smart Custom Fields API で調べると下記が一番に出てくるけど
構造の使いみちが限定的な形なので、そのまま繰り返すフィールドの塊でとったほうが良いと思う

https://yamashitive.com/281/
上記記事だと下記のような感じ
この形が良い場合は、参考にしてください

- scf
    - field-1
        - ほげ
        - ほげ2
    - field-2
        - ほげ
        - ほげ2
2
1
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
2
1