How to dynamically populate Advanced Custom Fields choice fields and select options

This guide aims to expand on the official documentation from ACF including support for default value setting. See official documentation on this feature at https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/

Our goal here is to target the ACF field we want to populate with choices, then add or remove choices, and finally add or remove default values to correspond to our choice changes. When we target an ACF field using the ACF load field filter we’re going to get an object $field that contains “choice” and “default_values” arrays.

add_filter( 'acf/load_field/name=core_blocks', function( $field ) { // Do stuff to $field; return $field; }

In this example from ACF Engine’s core block registration routine, we’re filtering a field with the key “core_blocks”. You can find your ACF field key on the field group’s UI page.

In this example instead of an anonymous function as the callback we use a named function:

function field_choices( $field ) {
  // Do stuff;
  return $field;
}

add_filter( 'acf/load_field/name=core_blocks', 'field_choices' );

As with any WordPress filter, it’s very important that you always return $field otherwise that field will be completely broken.

In this example from a PHP class context we’re using a method callable as the callback, and also shown here is completely clearing both “choices” and “default_value” arrays. This will create a working field, but with no options and no defaults.

public function field_choices( $field ) {

  $field['choices']        = array();
  $field['default_value']  = array();
  return $field;

}

add_filter( 'acf/load_field/name=core_blocks', array( $this, 'field_choices' ) );