Instructions for creating groups of nested options in dropdown lists with ACF – Learn WordPress from a to z

Tutorials 0 lượt xem

The drop-down list with nested group of options using <optgroup> is a basic but still missing feature in ACF.

In this article, we will learn how to create and use them like the image below. Let’s find out together!

result options nested dropdown list with acf

Formatting a nested option selection in a dropdown with ACF

nested option domains in dropdown with acf

The setting of Choices is just a simple textarea (shown as above), so we need to redefine what is the title of the group of options.

For this example, the line starting with # will be converted to the title of the group of options.

Here is my Choices setting :

#America
us : United States
ca : Canada
mx : Mexico
#Europe
uk : United Kingdom
de : German
fr : France
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
</div>

Using ACF Hooks

What I am trying to achieve is to create a nested array using the header of the options group. Then cast it to the choices array .

// Đừng quên thay đổi giá trị của 'name'
add_filter('acf/prepare_field/name=country', 'acf_allow_optgroup');

function acf_allow_optgroup( $field ) {
  if( $field['ID'] === 0 ) { return $field; }

  $raw_choices = $field['choices'];
  $choices = [];

  $current_group = '';
  foreach( $raw_choices as $value =&gt; $label ) {

    // Nếu chữ cái đầu tiên bắt đầu bằng "#", chuyển nó thành tiêu đề
    if( preg_match( '/^#(.+)/', $label, $matches ) ) {
      $current_group = str_replace( '#', '', $label );
      $choices[ $current_group ] = [];
    }
    // Nếu tiêu đề đã được định nghĩa từ trước
    elseif( !empty( $current_group ) ) {
      $choices[ $current_group ][ $value ] = $label;
    }
    else {
      $choices[ $value ] = $label;
    }
  }

  $field['choices'] = $choices;
  return $field;
}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span>28</span><span>29</span>
</div>

So you’re done! Don’t forget to change the value of the options to match your field.

Epilogue

This is a small guide to make it easier for you to customize your website with ACF.

If you find it interesting, you can follow the  WordPress basics section  to know more new knowledge.

Follow fanpage to receive the latest posts:  Group

Bài viết liên quan