wordpressプラグインでおなじみの、ACF(advanced Custom fields)
リピーターフィールド内のラジオボタンで、ラベルと値を出力しようとしてちょっと戸惑ったので備忘録です。
前提
まず、ACFのカスタムフィールドの設定は、
repeater_field_nameというリピーターフィールドの中に、btn_nameというラジオボタンのフィールドを設定し、
選択肢を、
3f : 3F
loft : ロフト
2f-only : 2Fまで
と設定しました。
で、「2f-only : 2Fまで」の時は値を表示しないようにしたかったのです。
上手くいかなかった出力方法
通常通りのリピーターフィールドとラジオボタンの出力のコードを書きました。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | <?php if ( have_rows( 'repeater_field_name' ) ): while ( have_rows( 'repeater_field_name' ) ) : the_row(); //ラジオボタンのデータを代入 $field = get_sub_field_object(‘field_name’); $value = get_sub_field(‘field_name’); $label = $field [‘choices’][ $value ]; ?> <?php if ( $value <> '2f-only' ):?> <p><?php echo $label ; ?> <?php endif ; endwhile ; else : // no rows found endif ; ?> |
これだと「Array」と表示されるだけ。まいったなぁと思ったときは頑張ってDocumentationを確認しましょう。
上手くいった出力方法
調べてみたら、get_sub_field_objectは、has_sub_fieldループ内で使用する必要があるようです。
なので、次のようにコードを修正。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 | <?php if ( get_field( 'repeater_field_name' ) ): while ( has_sub_field( 'repeater_field_name' ) ) : //ラジオボタンのデータを代入 $field = get_sub_field_object(‘field_name’); $btn_value = $field [ 'value' ]; $value = $btn_value [ 'value' ]; $label = $btn_value [‘label’]; ?> <?php if ( $value <> '2f-only' ):?> <p><?php echo $label ; ?> <?php endif ; endwhile ; else : // no rows found endif ; ?> |
ここまで至るのに諸々ありましたが、迷ったときはprint_r()関数で配列を全て出力してみると糸口をつかめます。
出力した配列
Array
(
[ID] => 6024
[key] => field_58e4c643fc29f
[label] => 3F または ロフト
[name] => repeater_field_name_0_field_name
[prefix] => acf
[type] => radio
[value] => Array
(
[value] => 2f-only
[label] => 2Fのみ
)
[menu_order] => 3
[instructions] => 3階建てまたはロフトをお選びください。
[required] => 0
[id] =>
[class] =>
[conditional_logic] => 0
[parent] => 6020
[wrapper] => Array
(
[width] =>
[class] =>
[id] =>
)
[_name] => field_name
[_prepare] => 0
[_valid] => 1
[choices] => Array
(
[3f] => 3F
[loft] => ロフト
[2f-only] => 2Fのみ
)
[allow_null] => 0
[other_choice] => 0
[save_other_choice] => 0
[default_value] => ロフト
[layout] => horizontal
[return_format] => array
)
誰かのお役にたれてば幸いです。