如何通过代码为ACF的Select字段添加选项并新增字段?
解决ACF字段的两个需求:添加年份选项与新增字段
一、为Year选择字段添加2023、2024、2025等年份选项
给ACF的Select类型字段添加选项,只需在该字段的配置数组中加入choices键,键值为关联数组——数组的键是存储到数据库的值,值是后台显示的选项文本。
修改后的Year字段配置片段:
array ( 'key' => 'year', 'label' => 'Year', 'name' => 'year', 'type' => 'select', 'prefix' => '', 'instructions' => '', 'required' => 1, 'conditional_logic' => 0, 'wrapper' => array ( 'width' => '33%', 'class' => 'year', 'id' => '', ), 'choices' => array( '2023' => '2023', '2024' => '2024', '2025' => '2025', // 可继续添加更多年份 ), 'default_value' => '', 'placeholder' => '', 'prepend' => '', 'append' => '', 'maxlength' => '', 'readonly' => 0, 'disabled' => 0, )
二、在字段组中添加Week和Term字段
在字段组的fields数组中新增两个Select类型的字段配置,分别设置它们的选项、宽度等属性即可。以下是完整的字段组代码:
if( function_exists('acf_add_local_field_group') ): acf_add_local_field_group(array ( 'key' => 'group_1', 'title' => 'My Group', 'fields' => array ( // Year字段(已添加年份选项) array ( 'key' => 'year', 'label' => 'Year', 'name' => 'year', 'type' => 'select', 'prefix' => '', 'instructions' => '', 'required' => 1, 'conditional_logic' => 0, 'wrapper' => array ( 'width' => '33%', 'class' => 'year', 'id' => '', ), 'choices' => array( '2023' => '2023', '2024' => '2024', '2025' => '2025', ), 'default_value' => '', 'placeholder' => '', 'prepend' => '', 'append' => '', 'maxlength' => '', 'readonly' => 0, 'disabled' => 0, ), // Week字段(12个选项) array ( 'key' => 'week', 'label' => 'Week', 'name' => 'week', 'type' => 'select', 'prefix' => '', 'instructions' => '', 'required' => 1, 'conditional_logic' => 0, 'wrapper' => array ( 'width' => '33%', 'class' => 'week', 'id' => '', ), 'choices' => array( 'week_1' => 'Week 1', 'week_2' => 'Week 2', 'week_3' => 'Week 3', 'week_4' => 'Week 4', 'week_5' => 'Week 5', 'week_6' => 'Week 6', 'week_7' => 'Week 7', 'week_8' => 'Week 8', 'week_9' => 'Week 9', 'week_10' => 'Week 10', 'week_11' => 'Week 11', 'week_12' => 'Week 12', ), 'default_value' => '', 'placeholder' => '', 'readonly' => 0, 'disabled' => 0, ), // Term字段(4个选项) array ( 'key' => 'term', 'label' => 'Term', 'name' => 'term', 'type' => 'select', 'prefix' => '', 'instructions' => '', 'required' => 1, 'conditional_logic' => 0, 'wrapper' => array ( 'width' => '33%', 'class' => 'term', 'id' => '', ), 'choices' => array( 'term_1' => 'Term 1', 'term_2' => 'Term 2', 'term_3' => 'Term 3', 'term_4' => 'Term 4', ), 'default_value' => '', 'placeholder' => '', 'readonly' => 0, 'disabled' => 0, ) ), 'location' => array ( array ( array ( 'param' => 'post_type', 'operator' => '==', 'value' => 'post', ), ), ), 'menu_order' => 0, 'position' => 'normal', 'style' => 'default', 'label_placement' => 'top', 'instruction_placement' => 'label', 'hide_on_screen' => '', )); endif;
补充说明
- 三个字段的
width均设为33%,后台会横向排列成一行(总宽度接近100%)。 - 可根据需求调整
required、default_value等属性,比如是否必填、默认选中项。 choices数组的键可自定义,存储到数据库的是键值,后台显示对应的文本。
内容的提问来源于stack exchange,提问作者Adam Fletcher
相关产品推荐
相关产品推荐

