Summary:
This article discusses how to create a dropdown list with nested groups of options using Advanced Custom Fields (ACF). The process involves defining the options groups in the Choices settings, and utilizing an ACF Hook to create a nested array for the choices. The code provided demonstrates how to achieve this customization in ACF. By following these steps, users can enhance their website customization with ACF. The article concludes with a suggestion to explore more WordPress-related content and follow the fan page for updates.
Dropdown list with nested group of options using <optgroup/>
is a basic feature but still missing in ACF. In this article, we will learn how to create and use them like the image below. Let’s find out!
Format nested option selection in dropdown list with ACF
Settings of Choices
is just a simple textarea cell (shown above), so we need to redefine it to know what the title of the group of options is. For this example, the line that starts with #
will be converted to the title of the options group. Here is the setting Choices
mine:
#America
us : United States
ca : Canada
mx : Mexico
#Europe
uk : United Kingdom
de : German
fr : France
Using ACF Hook
What I’m trying to achieve is to create a nested array using the title of the group of options. Then pass it into the array choices
.
// Đừ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 => $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;
}
And you’re done! Don’t forget to change the values of the weights to match your field.
Epilogue
Here is a small guide to help you customize your website with ACF more easily. If you find it interesting, you can follow the basic WordPress section to learn more new knowledge. Follow fanpage to receive the latest articles: Hocwordpress Group