acf_select_input()


Advanced Custom Fields (ACF) プラグインで使用されるacf_select_input()は、カスタムフィールドでの選択入力を処理する際に役立つ関数です。

構文

acf_select_input( array $args = array() );

引数の説明:

  • $args (array) — 関数に渡されるオプションの配列
  • choices (array) — 選択肢のリスト。キーと値のペアで指定。
  • default_value (string|array) — デフォルトの選択値。
  • multiple (boolean) — 複数選択を許可するかどうか。デフォルトはfalse
  • return_format (string) — 値の返却形式。デフォルトはvalue

例 1: 単一選択の基本的な使用例

以下のコードは、単一選択フィールドを作成する方法を示します。

acf_select_input( array(
    'choices' => array(
        'option_1' => '選択肢1',
        'option_2' => '選択肢2',
        'option_3' => '選択肢3'
    ),
    'default_value' => 'option_1'
) );

例 2: 複数選択を許可

複数選択を有効にした例です。

acf_select_input( array(
    'choices' => array(
        'red' => '赤',
        'blue' => '青',
        'green' => '緑'
    ),
    'multiple' => true
) );

例 3: デフォルト値を指定

デフォルトで'option_2'を選択状態にします。

acf_select_input( array(
    'choices' => array(
        'option_1' => '選択肢1',
        'option_2' => '選択肢2',
        'option_3' => '選択肢3'
    ),
    'default_value' => 'option_2'
) );

例 4: フォーマット指定で値を返す

return_formatarrayに設定することで配列形式で返します。

acf_select_input( array(
    'choices' => array(
        'cat' => '猫',
        'dog' => '犬',
        'bird' => '鳥'
    ),
    'return_format' => 'array'
) );

例 5: 条件付きで選択肢を動的に生成

条件に基づいて選択肢を生成します。

acf_select_input( array(
    'choices' => function() {
        if ( is_user_logged_in() ) {
            return array(
                'logged_in' => 'ログイン済みユーザー',
                'guest' => 'ゲストユーザー'
            );
        } else {
            return array(
                'guest' => 'ゲストユーザー'
            );
        }
    }
) );

注意事項

acf_select_input()を使用する際には、選択肢のキーと値を明確に定義してください。
必要に応じてデフォルト値を設定し、ユーザーが意図しない値を選択しないようにします。